基于事件的异步模式实现总是捕获当前的同步上下文吗?

问题描述:

我正在翻阅Bart De Smet的C#5.0 Unleashed书中的一些代码,并使用WebClient来玩弄它。基于事件的异步模式实现总是捕获当前的同步上下文吗?

在下面的代码中,我注意到回调是在UI线程上执行的。我知道EAP的执行WebClient.DownloadStringAsync捕获当前SynchronizationContext,并且是否所有的EAP实现都这样做,因为似乎没有办法指定SynchronizationContext执行回调。

这里是有问题的代码:

private void loadButton_Click(object sender, EventArgs e) 
    { 
     var client = new WebClient(); 

     client.DownloadStringCompleted += (o, args) => 
      { 
       if (args.Error != null) 
       { 
        try 
        { 
         throw args.Error; // simply to restore structured exception handling?! 
        } 
        catch (WebException) 
        { 
         this.textBox.Text = "ERROR: " + args.Error.Message; 
        } 

        return; 
       } 

       // Already on the UI thread! 
       this.textBox.Text = args.Result; 
      }; 

     client.DownloadStringAsync(new Uri(@"http:\\www.rpmglobal.com")); 
    } 
+0

你不能保证。 –

不,绝对不是。 WebClient's执行确实嗅探当前的SynchronizationContext当您进行呼叫时,最终会触发事件通知您(例如DownloadStringAsync),但这纯粹是实施特定的,并不是EAP的保证。