2014-03-05 2 views
0

Bart De Smet의 C# 5.0 Unleashed 책에서 코드를 찾아 보았는데 WebClient을 사용하여 놀았습니다.이벤트 기반 비동기 패턴 구현은 항상 현재 동기화 컨텍스트를 캡처합니까?

아래 코드에서 콜백이 UI 스레드에서 실행 된 것으로 나타났습니다. 나는 WebClient.DownloadStringAsync의 EAP 구현이 현재 SynchronizationContext을 캡처하고 어떤 SynchronizationContext 콜백을 실행할지를 지정하는 방법이 없기 때문에 EAP의 모든 구현이이를 수행하는지 여부를 방황하고 있었다는 것을 알고있다.

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

귀하는이를 보장하지 않습니다. –

답변

1

아니, 확실히 : 여기

문제의 코드입니다. WebClient's 구현 은 사용자에게 알림을 보내주기 위해 전화를 걸 때 현재 SynchronizationContext을 신고합니다 (예 : DownloadStringAsync). 이는 구현에 따라 다르며 EAP를 보장하지 않습니다.

관련 문제