Reputation: 1051
I try to wait for an HttpWebRequest to finish without writing a dozen 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.
The Problem now is that there appears a NotSupportedException everytime I call it and I don´t understand why. 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
Upvotes: 1
Views: 670
Reputation: 25
Use this handler...
while ((GetRequestStreamResult.AsyncWaitHandle.WaitOne(1000, true) == false)
&& (GetRequestStreamResult.IsCompleted == false))
{
// Do nothing
}
Upvotes: 0
Reputation: 1051
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. And this simply throws a NotSupportedException in any case when accessing the AsyncWaitHandle getter.
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
Upvotes: 2