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;
什麼是做到這一點的最好方法是什麼?
THX的答覆...你認爲我可以只是這樣做:Dispatcher.BeginInvoke(()=> {messateToReturn = 「」 東西「;}); – jojo
沒有,因爲即使該方法將執行異步,並且不能保證當你返回messageToReturn時調用會完成,如果你真的想阻塞線程直到響應返回,檢查ManualResetEvent,但請謹慎操作!因爲它會鎖定你的UI。 –