I want a webrequest running in a background thread, and then for the callback to be handled in the UI 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 should happen:
"Start the request"
"Continue with normal UI code"
.
.
.
"Response"
But I get:
"Start the request"
.
.
.
"Response"
"Continue with normal UI code"
It's like request.GetResponse()
stops the entire thread independent of StartNew. Any ideas? I am using MonoDevelop (Mono for Android).
Edit: According to Mono for Android documentation
"Tasks created with the Parallel Task Library can run asynchronously and return on their calling thread, making them very useful for triggering long-running 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 have a better way of doing background call + UI-thread-callback I'm open to suggestions. Tried BeginGetResponse / EndGetResponse but the callback where not run on the UI thread.