Run an async function in another thread

后端 未结 3 674
深忆病人
深忆病人 2021-01-31 10:55

I\'m evaluating the Async CTP.

How can I begin execution of an async function on another thread pool\'s thread?

static async Task Test()
{
    // Do some         


        
3条回答
  •  不知归路
    2021-01-31 11:29

    There would be, if this wasn't a console application. For example, if you do this in a Windows Forms application, you could do:

    // Added to a button click event, for example
    public async void button1_Click(object sender, EventArgs e)
    {
        // Do some stuff
        await Test();
        // Do some more stuff
    }
    

    However, there is no default SynchronizationContext in a console, so that won't work the way you'd expect. In a console application, you need to explicitly grab the task and then wait at the end.

    If you're doing this in a UI thread in Windows Forms, WPF, or even a WCF service, there will be a valid SynchronizationContext that will be used to marshal back the results properly. In a console application, however, when control is "returned" at the await call, the program continues, and just exits immediately. This tends to mess up everything, and produce unexpected behavior.

提交回复
热议问题