GetResponse works in Task.Factory.StartNew

I want webrequest to work in the background thread, and then to handle the callback in the user interface thread. Here is my code:

Task.Factory.StartNew(() => { Console.Out.WriteLine("Start the request"); return request.GetResponse(); } ).ContinueWith(t => { Console.Out.WriteLine("Response"); using (HttpWebResponse response = (HttpWebResponse)t.Result) { string responseBody = ... } }, TaskScheduler.FromCurrentSynchronizationContext()); Console.Out.WriteLine("Continue with normal UI code"); } 

What is going to happen:

 "Start the request" "Continue with normal UI code" . . . "Response" 

But I get:

 "Start the request" . . . "Response" "Continue with normal UI code" 

It kind of request.GetResponse() stops the whole thread regardless of StartNew. Any ideas? I am using MonoDevelop (Mono for Android).

Edit: According to Mono for Android documentation

"Tasks created using the parallel task library can be performed asynchronously and return to their calling thread, which makes them very useful for starting lengthy operations without blocking the user interface.

A simple parallel task operation might look like this: "

 using System.Threading.Tasks; void MainThreadMethod () { Task.Factory.StartNew (() => wc.DownloadString ("http://...")).ContinueWith ( t => label.Text = t.Result, TaskScheduler.FromCurrentSynchronizationContext() ); } 

So my solution should work!

If anyone has a better way to make a background call + UI-thread-callback, I am open to suggestions. Tried BeginGetResponse / EndGetResponse, but a callback that does not start in the user interface thread.

+4
source share
1 answer

Task.Factory.StartNew() does not start a new thread as such; instead, it allows you to call the method entry point again without being blocked while it passes the current method call. How this happens under the hood is a little tricky, but using it is not the โ€œstart a new thread and run this codeโ€ approach. In addition, there is no reason why a processor would not decide to run code on a thread before exiting the calling thread. This is up to the thread scheduler.

+2
source

All Articles