我希望在后台线程中运行一个the请求,然后在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 (MonoDevelop)。
编辑:基于用于Android文档的Mono的
“使用并行任务库创建的任务可以异步运行并返回它们的调用线程,这使得它们在不阻塞用户界面的情况下触发长时间运行的操作非常有用。 简单的并行任务操作可能如下所示:“
using System.Threading.Tasks;
void MainThreadMethod ()
{
Task.Factory.StartNew (() => wc.DownloadString ("http://...")).ContinueWith (
t => label.Text = t.Result, TaskScheduler.FromCurrentSynchronizationContext()
);
}
所以我的解决方案应该有效!
如果有人有更好的方法进行后台调用+UI线程回调,我愿意接受建议。尝试了BeginGetResponse / EndGetResponse,但是在UI线程上没有运行的回调。
发布于 2013-02-20 08:21:01
Task.Factory.StartNew()
本身不会启动新线程,而是允许再次调用方法入口点,而不会在传递当前方法调用时被阻塞。在幕后如何发生这种情况有点复杂,但使用它并不是一种“启动新线程并运行此代码”的方法。最重要的是,cpu没有理由在退出调用线程之前决定在线程中运行代码。这取决于线程调度程序。
https://stackoverflow.com/questions/14984480
复制