[英]NotSupportedException when calling AsyncWaitHandle.WaitOne on non-UI Thread
I try to wait for an HttpWebRequest to finish without writing a dozen AsyncCallbacks. 我尝试等待HttpWebRequest完成而不编写十几个AsyncCallbacks。 For that I tried to handle the call in a Task and use WaitOne within it --> so the ui thread will not be blocked. 为此,我尝试处理Task中的调用并在其中使用WaitOne->以便不会阻塞ui线程。
The Problem now is that there appears a NotSupportedException everytime I call it and I don´t understand why. 现在的问题是,每次我调用它时都会出现一个NotSupportedException,但我不明白为什么。 Can someone tell me more about that and maybe how to fix this issue? 有人可以告诉我更多有关此的信息,也许还可以解决此问题吗?
Here the code: 这里的代码:
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);
}
Best regards 最好的祝福
Christoph 克里斯托夫
I found this article . 我找到了这篇文章 。 That pointed me to the direction that maybe it is no common silverlight issue, but a Problem with the actual implementation of the IAsyncResult which is of System.Net.Browser.OHWRAsyncResult. 这向我指出了一个方向,也许这不是常见的Silverlight问题,而是IAsyncResult的实际实现的问题,它是System.Net.Browser.OHWRAsyncResult。 And this simply throws a NotSupportedException in any case when accessing the AsyncWaitHandle getter. 而且在访问AsyncWaitHandle getter时无论如何都会抛出NotSupportedException。
I helped me out by writing this small Extension method: 我通过编写以下扩展方法来帮助我:
private static void WaitForIt(this IAsyncResult result)
{
while (!result.IsCompleted)
{
Thread.Sleep(50);
}
}
Not really pretty but it works... 不是很漂亮但是可以用...
Regards 问候
Christoph 克里斯托夫
Use this handler... 使用此处理程序...
while ((GetRequestStreamResult.AsyncWaitHandle.WaitOne(1000, true) == false)
&& (GetRequestStreamResult.IsCompleted == false))
{
// Do nothing
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.