【发布时间】:2013-02-21 03:03:50
【问题描述】:
我希望在后台线程中运行 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(Android 的 Mono)。
编辑:根据Mono for Android documentation
"使用并行任务库创建的任务可以异步运行 并返回他们的调用线程,使他们非常有用 在不阻塞用户的情况下触发长时间运行的操作 界面。
一个简单的并行任务操作可能如下所示:"
using System.Threading.Tasks;
void MainThreadMethod ()
{
Task.Factory.StartNew (() => wc.DownloadString ("http://...")).ContinueWith (
t => label.Text = t.Result, TaskScheduler.FromCurrentSynchronizationContext()
);
}
所以我的解决方案应该有效!
如果有人有更好的方法来进行后台调用 + UI-thread-callback,我愿意接受建议。尝试了 BeginGetResponse / EndGetResponse 但回调不在 UI 线程上运行。
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# .net mono xamarin.android