Frederik Frederik - 28 days ago 12
HTTP Question

Returning a HTTP response data from a function in a multithreaded manner (C# / VB )

I know about the

IAsyncResult
approach, however from my experimentation this still momentarily freezes the UI a little - which is weird to me. I've Google'd a lot and I cannot seem to find a way to implement this that does not freeze the UI a little.

What I want is for a function to return data from a
HttpWebReqeust
in a threaded manner. I need a good way to do this, and not threading it, and then setting some variable to
true
and storing the response in a shared variable.

Any way to do this?

Answer

The code you've mentioned from the MSDN do block the UI because of these lines:

Thread.Sleep(0);
Console.WriteLine("Main thread {0} does some work.",
    Thread.CurrentThread.ManagedThreadId);

// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();

You can see here a blocking wait for a execution to be complete. So for a async way to get the HttpResponse you can easily use the async/await keywords, with dozens of the sample code:

// inside the method marked as async
// prepare the Web Request
Task<WebResponse> getResponseTask = req.GetResponseAsync();
WebResponse response = await getResponseTask;
// process your result in the same context which have fired the request
Comments