有什么用异步/的await / TPL这两个函数之间的区别? [英] What is the difference between these two functions using async/await/TPL?

查看:294
本文介绍了有什么用异步/的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 a Task?

解决方案

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).

这篇关于有什么用异步/的await / TPL这两个函数之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆