What is the difference between these two functions using async/await/TPL?

徘徊边缘 提交于 2019-12-23 19:42:59

问题


I think I have successfully confused myself for the day.

public void DoSomething1()
{
    Task.Delay(1000);
}

public async void DoSomething2()
{
    await Task.Delay(1000);
}

What is the difference between these two functions in terms of what happens within them when they are called? What is the purpose of using an async method that does not return a Task?


回答1:


What is the difference between these two functions in terms of what happens within them when they are called?

DoSomething1 is a synchronous method. As such:

  • It starts an asynchronous delay and then ignores it.
  • Any exceptions from the asynchronous delay are silently ignored.
  • Any exceptions from DoSomething are raised directly to the caller.

DoSomething2 is an asynchronous void method. As such:

  • It starts an asynchronous delay and then observes it.
  • Any exceptions from the asynchronous delay are re-raised on the SynchronizationContext that was current at the time DoSomething2 started executing. This generally results in program termination.
  • Any exceptions from DoSomething2 are also raised on that SynchronizationContext, with the same result.

What is the purpose of using an async method that does not return a Task?

async void is not a natural thing. For example, the equivalent simply does not exist in F#. async void was added to C#/VB to enable event handlers to become asynchronous without changing the entire event handling or delegation system.

In short, you should avoid async void, and only use them for event handlers (or logical equivalents to event handlers, like ICommand.Execute in MVVM).



来源:https://stackoverflow.com/questions/35023696/what-is-the-difference-between-these-two-functions-using-async-await-tpl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!