2013-10-29 46 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 
      }