How does running several tasks asynchronously on UI thread using async/await work?

前端 未结 3 1286
旧时难觅i
旧时难觅i 2020-12-15 10:58

I\'ve read (and used) async/await quite a lot for some time now but I still have one question I can\'t get an answer to. Say I have this code.

private async          


        
3条回答
  •  长情又很酷
    2020-12-15 11:11

    The TaskParallelLibrary (TPL) uses a TaskScheduler which can be configured with TaskScheduler.FromCurrentSynchronizationContext to return to the SynchronizationContext like this :

    textBox1.Text = "Start";
    // The SynchronizationContext is captured here
    Factory.StartNew( () => DoSomeAsyncWork() )
    .ContinueWith( 
        () => 
        {
           // Back on the SynchronizationContext it came from            
            textBox1.Text = "End";
        },TaskScheduler.FromCurrentSynchronizationContext());
    

    When an async method suspends at an await, by default it will capture the current SynchronizationContext and marshall the code after the await back on the SynchronizationContext it came from.

            textBox1.Text = "Start";
    
            // The SynchronizationContext is captured here
    
           /* The implementation of DoSomeAsyncWork depends how it runs, this could run on the threadpool pool 
              or it could be an 'I/O operation' or an 'Network operation' 
              which doesnt use the threadpool */
            await DoSomeAsyncWork(); 
    
            // Back on the SynchronizationContext it came from
            textBox1.Text = "End";
    

    async and await example:

    async Task MyMethodAsync()
    {
      textBox1.Text = "Start";
    
      // The SynchronizationContext is captured here
      await Task.Run(() => { DoSomeAsyncWork(); }); // run on the threadPool
    
      // Back on the SynchronizationContext it came from
      textBox1.Text = "End";
    }
    

提交回复
热议问题