我想在后台线程中运行webrequest,然后在UI线程中处理回调.这是我的代码:
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");
}
会发生什么:
"Start the request"
"Continue with normal UI code"
.
.
.
"Response"
但我得到:
"Start the request"
.
.
.
"Response"
"Continue with normal UI code"
就像request.GetResponse()停止整个线程独立于StartNew.有任何想法吗?我正在使用MonoDevelop(Mono for Android).
编辑:根据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()
);
}
所以我的解决方案应该有效
如果有人有更好的方法来进行后台调用UI线程回调,我会接受建议.尝试使用BeginGetResponse / EndGetResponse但不在UI线程上运行的回调.
最佳答案 Task.Factory.StartNew()本身不会启动新的线程,而是允许再次调用方法入口点,而不会在当前方法调用时被阻塞.如何在引擎盖下发生这种情况有点复杂,但使用它并不是“启动新线程并运行此代码”方法.最重要的是,没有理由为什么cpu在退出调用线程之前不会决定在Thread内运行代码.这取决于线程调度程序.