难道一个异步方法无效创建一个新线程每次它被称为? [英] Does an async void method create a new thread everytime it is called?

查看:165
本文介绍了难道一个异步方法无效创建一个新线程每次它被称为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情形:

 异步无效DoStuff(){
    // ...
}button1.Click + =(S,P)=> {
    做东西();
};

我不知道,当我叫异步无效方法,而第一个呼叫仍然是不完整会发生什么。
将在调用创建一个新线程每次它被调用或将通话破坏并覆盖创建了previous线程?另外,如果将前者的假设是正确的局部变量的方法可以共享?

编辑:

我误解了异步的await 的事情,因为在Windows 8的应用程序,它的行为不同。如果您认为调用异步方法是一样创造像我这样一个新的线程,请阅读的此澄清aricle


解决方案

  

我不知道当我打电话异步方法无效不止一次在同一时间发生的事情


如果在第一次调用仍然是不完整(潜在的暂停)发生了另一次调用你的意思是?它会工作得很好。有没有压倒一切,没有破坏。你会用状态机的另一个实例结束(这是编译器生成什么你)。

这两个状态机将拥有完全独立的局部变量等。当然,只有一个可以真正的运行的时间,除非在某个地方你避免捕获的背景下​​异步方法。

不要忘了启动异步方法的的开始一个新的线程。一些异步操作开始的的异步方法可能会启动新的线程,但是这是一个不同的问题。生成的code中没有创建一个新的线程。

I have the following scenario:

async void DoStuff() {
    // ...
}

button1.Click += (s, p) => {
    DoStuff();
};

I'm not sure what happens when I call an async void method while the first call is still incomplete. Will the call create a new thread everytime it is called or will the call destroy and override the previous thread created? Also, will the local method variables be shared if the former assumption is right?

EDITED:

I had misunderstood the async await thing because in windows 8 apps, it behaves differently. If you thought that calling an async method was the same as creating a new thread like me, please read this clarifying aricle.

解决方案

I'm not sure what happens when I call an async void method more than once at the same time

You mean if another call occurs while the first call is still incomplete (potentially "paused")? It will work just fine. There's no "overriding", no "destroying". You'll end up with another instance of the state machine (which is what the compiler builds for you).

The two state machines will have entirely separate local variables etc. Of course, only one of them can actually run at a time, unless somewhere in the async method you avoid capturing the context.

Don't forget that starting an async method doesn't start a new thread. Some async operations you start within the async method may start new threads, but that's a different matter. Nothing within the generated code creates a new thread.

这篇关于难道一个异步方法无效创建一个新线程每次它被称为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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