2011-10-30 52 views
0

我正在處理異步Web請求。並且需要依賴於做出消息返回的響應。如何修改不在同一線程中的對象

想做某事像下面

// creating request 

string messageToReturn = string.empty; 
request.BeginGetResponse(ar => 
      { 
       HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState; 
       var response = (HttpWebResponse)req2.EndGetResponse(ar); 

       // is it safe to do this? 
       messageToReturn = "base on respone, assign different message"; 


      }, request); 

// will i get any response message? i will always get empty right? 
// since response is handle in another thread 
return messageToReturn; 

什麼是做到這一點的最好方法是什麼?

回答

0

你說得對,那個變量將永遠是空的,因爲你用BeginGetResponse方法啓動了異步請求。所以你真的有幾個選擇。您可以阻止正在執行的線程,直到響應返回(可能是一個非常糟糕的主意,除非您有足夠的參數來做到這一點),或者您可以使用基於事件的異步模式在響應返回時提醒呼叫者...

考慮一些你的代碼包裝在一個方法

public void GetMessageAsync() 
{ 
    string messageToReturn = string.empty; 
    request.BeginGetResponse(ar => 
      { 
       HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState; 
       var response = (HttpWebResponse)req2.EndGetResponse(ar); 

       // is it safe to do this? 
       messageToReturn = "base on respone, assign different message"; 


      }, request); 
} 

到這裏線了基於事件模式。我們定義了一個自定義的EventArgs類和一個自定義事件,這些事件可以讓調用者收聽,並在響應返回時觸發。

public class StringEventArgs : EventArgs 
{ 
    public string Message { get; set; } 
} 

public event EventHandler<StringEventArgs> MessageReturned; 

public void GetMessageAsync() 
{ 
    //string messageToReturn = string.empty; 
    request.BeginGetResponse(ar => 
      { 
       HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState; 
       var response = (HttpWebResponse)req2.EndGetResponse(ar); 

       //messageToReturn = "base on respone, assign different message"; 
       this.MessageReturned(this, new StringEventArgs { Message = response.ToString() }); 

      }, request); 
} 
+0

THX的答覆...你認爲我可以只是這樣做:Dispatcher.BeginInvoke(()=> {messateToReturn = 「」 東西「;}); – jojo

+0

沒有,因爲即使該方法將執行異步,並且不能保證當你返回messageToReturn時調用會完成,如果你真的想阻塞線程直到響應返回,檢查ManualResetEvent,但請謹慎操作!因爲它會鎖定你的UI。 –

相關問題