在.NET 4.0中,替代await关键字的最佳选择是什么?我有一个需要在异步操作之后返回值的方法。我注意到wait()方法会完全阻塞线程,从而使异步操作无用。在释放UI线程的同时运行异步操作的选项是什么?
在.NET 4.0中,替代await关键字的最佳选择是什么?我有一个需要在异步操作之后返回值的方法。我注意到wait()方法会完全阻塞线程,从而使异步操作无用。在释放UI线程的同时运行异步操作的选项是什么?
Task
和.ContinueWith()
。但这意味着您必须在异常处理和流程控制方面付出一些努力。ContinueWith()
与for
循环或try-catch
块等命令式构造不兼容的原因。因此,引入了async
和await
,以便编译器可以帮助我们。你可以使用yield
协程来实现类似于await
的行为,我在非4.5代码中使用了这种方法。你需要一个YieldInstruction
类,它是从应该运行异步的方法中检索到的:
public abstract class YieldInstruction
{
public abstract Boolean IsFinished();
}
接下来你需要一些 YieldInstruction
的实现(例如 TaskCoroutine
处理任务),并按照以下方式使用它(伪代码):
public IEnumerator<YieldInstruction> DoAsync()
{
HttpClient client = ....;
String result;
yield return new TaskCoroutine(() => { result = client.DownloadAsync(); });
// Process result here
}
for (Coroutine item in coroutines)
{
if (item.CurrentInstruction.IsFinished())
{
// Move to the next instruction and check if coroutine has been finished
if (item.MoveNext()) Remove(item);
}
}
当开发WPF或WinForms应用程序时,如果您在正确的时间更新协程,也可以避免任何Invoke
调用。您还可以扩展这个想法,使您的生活更加轻松。示例:
public IEnumerator<YieldInstruction> DoAsync()
{
HttpClient client = ....;
client.DownloadAsync(..);
String result;
while (client.IsDownloading)
{
// Update the progress bar
progressBar.Value = client.Progress;
// Wait one update
yield return YieldInstruction.WaitOneUpdate;
}
// Process result here
}