如何异步等待任务完成

时间:2019-04-29 15:07:30

标签: c# multithreading asynchronous task-parallel-library wait

我正在编写一段触发多个任务的代码,最后我需要等待一个任务完成才能继续前进。

示例代码-

def on_button_1(event):
    global result 
    result = on_left_click("GO")

def on_button_3(event):
    global result 
    result = on_right_click("STOP")

frame.bind("<Button-1>", on_button_1)
frame.bind("<Button-3>", on_button_3)

如果我在var taskToWaitOn = Task.Factory.StartNew(Method1); Task.Factory.StartNew(Method2); Task.Factory.StartNew(Method3); taskToWaitOn.Wait(); 上等待,实际上是在阻塞线程,因此在4线程处理器中,我的处理能力将损失25%。

有没有一种方法可以让我以异步方式等待该任务,其中,线程实际上不会在等待时被阻塞,而是可以自由处理其他逻辑。

1 个答案:

答案 0 :(得分:-1)

使用异步/等待键将完成您想要的工作。

The Task asynchronous programming model in C#

public async Task testMethod() {
    callToSyncMethod(); // This will block the thread
    await callToAsyncMethod; // This will not
    callToAnotherSyncMethod(); // This will block but executed after the async is complete
}
相关问题