gpt4 book ai didi

c# - 使用 async 代替 Task.Run()

转载 作者:行者123 更新时间:2023-12-02 10:51:08 24 4
gpt4 key购买 nike

我有以下代码:

private void btnAction_Click(object sender, RoutedEventArgs e)
{

/** Clear the results field */
txtResult.Text = "";

/** Disable the button and show waiting status */
btnAction.IsEnabled = false;
lblStatus.Text = "Wait...";

/** Get input from the query field */
string input = query.Text;

/** Run a new task */
Task.Run(() => {

// calling a method that takes a long time (>3s) to finish and return
var attempt = someLibrary.doSomethingWith(input);

// return the result to the GUI thred
this.Dispatcher.Invoke(() =>
{

if (attempt.ContainsKey("success"))
{
if (attempt["success"] == true)
{
txtResult.Text = "Success! The door is: " + (attempt["is_open"] ? "open" : "closed");
lblStatus.Text = "";
}
else
{
lblStatus.Text = "Error! The service says: " + attempt["errorMessage"];
}
}

else
{
MessageBox.Show("There was a problem getting results from web service.");
lblStatus.Text = "";
}

/** Re-enable the button */
btnAction.IsEnabled = true;

});
});

}

现在,我想:

  • 以使用回调的方式编写相同的代码,而不是使用 Dispatcher.Invoke()
  • 能够取消调用 doSomething() 的正在运行的任务
  • 能够链接多个调用,即等待 doSomething() 并在完成后使用上一次调用的结果 doAnotherThing()

这就是为什么我想使用异步模型来编写它。

我该怎么办?

最佳答案

您可以将您的方法标记为asyncawait Task.Run,以便延续UI,也只保留长时间运行(看似受 CPU 限制)作业

private async void btnAction_Click(object sender, RoutedEventArgs e)
{
btnAction.IsEnabled = false;
txtResult.Text = "";
lblStatus.Text = "Wait...";

string input = query.Text;

// calling a method that takes a long time (>3s) to finish and return
var attempt = await Task.Run(() => someLibrary.doSomethingWith(input));

if (attempt.ContainsKey("success"))
{
if (attempt["success"] == true)
{
txtResult.Text = "Success! The door is: " + (attempt["is_open"] ? "open" : "closed");
lblStatus.Text = "";
}
else
{
lblStatus.Text = "Error! The service says: " + attempt["errorMessage"];
}
}
else
{
MessageBox.Show("There was a problem getting results from web service.");
lblStatus.Text = "";
}

btnAction.IsEnabled = true;

}

更新

要取消任务,您可以使用 CancellationTokenSource 实例中的 CancellationToken 并将其传递到 Task.Run 以及您的 long运行方法来检查 IsCancellationRequested (如果可以的话)。您可以通过调用 CancellationTokenSource.Cancel

取消

请注意,您可能希望将其包装在 try catch finally 中,并捕获 OperationCanceledException 并将按钮启用代码放在 finally

关于c# - 使用 async 代替 Task.Run(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60291612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com