2013-10-29 48 views
1

我嘗試等待HttpWebRequest完成而無需編寫一打AsyncCallbacks。爲此,我嘗試在Task中處理調用,並在其中使用WaitOne - >以便ui線程不會被阻塞。NotSupportedException當在非UI線程上調用AsyncWaitHandle.WaitOne線程

現在的問題是,每次我打電話時都會出現NotSupportedException,我不明白爲什麼。有人可以告訴我更多關於這個問題,也許如何解決這個問題?

下面的代碼:

Task.Factory.StartNew((x)=> 
      { 


      HttpWebRequest request = WebRequest.CreateHttp(baseUri + "/api/" + ControllerName); 
      request.Method = "POST"; 
      request.ContentType = "application/json"; 
      request.Headers["Session"] = SessionKey; 

      IAsyncResult GetRequestStreamResult = request.BeginGetRequestStream(null, null); 
      GetRequestStreamResult.AsyncWaitHandle.WaitOne(); //<-- That causes the exception 
      using (Stream RequestStream = request.EndGetRequestStream(GetRequestStreamResult)) 
      { 
       DataContractJsonSerializer serializer = new DataContractJsonSerializer(Parameter.GetType()); 
       serializer.WriteObject(RequestStream, Parameter); 
      } 

問候

克里斯托夫

回答

2

我發現這個article。這指出了可能這不是常見的Silverlight問題的方向,而是實際實現System.Net.Browser.OHWRAsyncResult的IAsyncResult的問題。在訪問AsyncWaitHandle獲取器時,這隻會引發NotSupportedException。

我幫了我寫這個小擴展方法:

private static void WaitForIt(this IAsyncResult result) 
    { 
     while (!result.IsCompleted) 
     { 
      Thread.Sleep(50); 
     } 
    } 

不是很漂亮,但它的工作原理...

問候

克里斯托夫

+0

這相當糟糕。在任務中使用BeginGetRequestStream()沒有意義。任務已經是異步的,所以只需使用GetRequestStream()。 –

+1

@HansPassant注意到我在silverlight上下文中。沒有像「GetRequestStream」這樣的方法。 – christoph

0

使用此處理.. 。

while ((GetRequestStreamResult.AsyncWaitHandle.WaitOne(1000, true) == false) 
      && (GetRequestStreamResult.IsCompleted == false)) 
      { 
       // Do nothing 
      }