等待异步方法而不阻塞线程

Joe*_*oel 2 c# wpf asynchronous async-await .net-4.5

如何在UpdateTasklist()方法之后执行SubmitWorkitem()方法而不阻塞线程?

private async void SubmitWorkitem(Workitem workitem)
{
    await Task.Run(() => this.SubmitWorkitem(workitem));

    //UpdateTasklist() should be executed after SubmitWorkitem() method.
    //How can i achieve this without blocking the UI thread?
    var locator = new ViewModelLocator();
    locator.Task.UpdateTasklist();
}
Run Code Online (Sandbox Code Playgroud)

编辑:

UpdateTasklist()方法连接到wcf webservice并要求所有打开的工作项.在SubmitWorkitem()方法中提交的工作项目仍然是答复的一部分.我认为这是因为UpdateTasklist()在提交工作项目之前执行.

请注意,这UpdateTasklist()也是一种异步方法

Mar*_*ell 5

重要提示:请勿ASYNC VOID编写方法(除非您正在编写事件处理程序)

对于其余的:

这已经是您的代码中发生的事情; 这就是await 意味着什么; 基本上,您的DifferentClass.UpdateTasklist();方法作为继承的一部分发生,当且仅当第一个task(this.SubmitWorkitem(workitem))完成时才会被调用.

有了您的编辑,还有就是缺少步:你应该await第二种方法,否则该方法不能报告完成/失败(IIRC编译器也会唠叨你):

private async Task SubmitWorkitem(Workitem workitem)
{
    await Task.Run(() => this.SubmitWorkitem(workitem));
    var locator = new ViewModelLocator();
    await locator.Task.UpdateTasklist();
}
Run Code Online (Sandbox Code Playgroud)

  • @Joel嗯,我想这必须和事件处理程序一样; 也许正确的指导是"不要写一个异步void方法,除非你别无选择" - 但是,请记住,这里的跑步者将*没有线索*你的方法是否已经完成 - 就框架而言,如果我们假设等待的操作实际上没有同步完成,这可能会发生,但这听起来不太可能,这个方法将在它到达第一个`await`时"结束".关键是...也许会遇到麻烦 (3认同)
  • @Joel:在这种情况下你确实需要一个`async void``ICommand.Execute`实现,但是你可以在`async Task`方法后面"隐藏"它.这为您提供了一个更好的API,您可以直接使用它,例如,在单元测试时.一个简单的`AsyncCommand`类型是[这里](http://stackoverflow.com/a/15743118/263693),我写了一个更复杂的[这里](https://nitoasyncex.codeplex.com/SourceControl/latest#源极/ Nito.AsyncEx.Mvvm%20(NET45,%20Win8,%20SL4,%20WP75)/AsyncCommand.cs). (2认同)