有什么用异步/的await / TPL这两个函数之间的区别? [英] What is the difference between these two functions using async/await/TPL?
问题描述
我想我已经成功地迷惑自己的一天。
公共无效DoSomething1()
{
Task.Delay(1000);
}公共异步无效了doSomething2()
{
等待Task.Delay(1000);
}
是在什么范围内它们会发生什么条件这两个函数的区别,他们被称为什么时候?什么是使用异步
的目的,方法不返回工作
?
是什么在被调用时在其中发生了什么条件这两个函数的区别?
块引用>
DoSomething1
是一个同步的方法。因此:
- 这会启动一个异步延迟的,然后忽略它的
- 从异步延迟的任何异常都忽略。
- 从
DoSomething的任何例外
直接提出给调用者。
了doSomething2
是一个异步无效
方法。因此:
- 这会启动一个异步延迟的,然后观察它的
- 从异步延迟的任何异常都在
的SynchronizationContext
这是当时电流了doSomething2
开始重新募集执行。这通常会导致程序终止。- 从
了doSomething2
的任何异常都也提出了在该的SynchronizationContext
,具有相同的结果。
什么是使用异步方法不返回任务的目的是什么?
块引用>
异步无效
不是一个自然的事。例如,等效根本不F#中存在。异步无效
添加到C#/ VB,以使事件处理程序,而不改变整个事件处理或委托系统成为异步的。总之,你应该避免
异步无效
,只将其用于事件处理(或逻辑等同事件处理程序,如ICommand.Execute
在MVVM)。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 aTask
?解决方案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 asynchronousvoid
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 timeDoSomething2
started executing. This generally results in program termination.- Any exceptions from
DoSomething2
are also raised on thatSynchronizationContext
, 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, likeICommand.Execute
in MVVM).这篇关于有什么用异步/的await / TPL这两个函数之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!