Frederik Frederik - 1 year ago 83
HTTP Question

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

I know about the

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
in a threaded manner. I need a good way to do this, and not threading it, and then setting some variable to
and storing the response in a shared variable.

Any way to do this?

Answer Source

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

Console.WriteLine("Main thread {0} does some work.",

// Wait for the WaitHandle to become signaled.

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download