简体   繁体   English

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

[英]Wait for async method without blocking the thread

How can i execute the UpdateTasklist() Method after the SubmitWorkitem() Method without blocking the thread? 如何在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();
}

EDIT: 编辑:

The UpdateTasklist() method connects to an wcf webservice and asks for all open workitems. UpdateTasklist()方法连接到wcf Web服务,并要求所有打开的工作项。 The workitem which is submitted in the SubmitWorkitem() Method is still part of the reply. SubmitWorkitem()方法中提交的工作项仍然是答复的一部分。 I thought that would be because UpdateTasklist() is executed before the submission of the workitem is done. 我认为那是因为UpdateTasklist()在提交工作项之前已执行。

Note that UpdateTasklist() is also an async method 请注意, UpdateTasklist()也是一个异步方法

Important: DO NOT WRITE ASYNC VOID METHODS (unless you are writing an event-handler) 重要提示: 请勿编写ASYNC VOID方法 (除非您正在编写事件处理程序)

For the rest: 对于其余的:

That is already what happens in your code; 这已经在您的代码中发生了; this is what await means ; 这是await 意思 ; basically, your DifferentClass.UpdateTasklist(); 基本上,您的DifferentClass.UpdateTasklist(); method happens as part of the continuation that gets invoked when and only when the first task ( this.SubmitWorkitem(workitem) ) completes. 方法仅在第一个任务( this.SubmitWorkitem(workitem) )完成时才作为连续调用的一部分发生。

With your edit, there is a missing step: you should await the second method, otherwise the method cannot report completion / failure (IIRC the compiler will also nag you): 有了您的编辑, 存在丢失的一步:你应该await第二个方法,否则该方法不能报告完成/失败(IIRC编译器也会唠叨你):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM