[英]Task continuation on UI thread, when started from background thread
If the following code is run on the background thread , how can I 'ContinueWith' on the main thread? 如果在后台线程上运行以下代码,我怎么能在主线程上'ContinueWith'?
var task = Task.Factory.StartNew(() => Whatever());
task.ContinueWith(NeedThisMethodToBeOnUiThread), TaskScheduler.FromCurrentSynchronizationContext())
The above will not work, because the current synchronization context is already a background thread. 以上操作无效,因为当前同步上下文已经是后台线程。
You need to get a reference to TaskScheduler.FromCurrentSynchronizationContext() from the UI thread and pass it to the continuation. 您需要从UI线程获取对TaskScheduler.FromCurrentSynchronizationContext()的引用,并将其传递给continuation。
Similar to this. 与此类似。 http://reedcopsey.com/2009/11/17/synchronizing-net-4-tasks-with-the-ui-thread/
http://reedcopsey.com/2009/11/17/synchronizing-net-4-tasks-with-the-ui-thread/
private void Form1_Load(object sender, EventArgs e)
{
// This requires a label titled "label1" on the form...
// Get the UI thread's context
var context = TaskScheduler.FromCurrentSynchronizationContext();
this.label1.Text = "Starting task...";
// Start a task - this runs on the background thread...
Task task = Task.Factory.StartNew( () =>
{
// Do some fake work...
double j = 100;
Random rand = new Random();
for (int i = 0; i < 10000000; ++i)
{
j *= rand.NextDouble();
}
// It's possible to start a task directly on
// the UI thread, but not common...
var token = Task.Factory.CancellationToken;
Task.Factory.StartNew(() =>
{
this.label1.Text = "Task past first work section...";
}, token, TaskCreationOptions.None, context);
// Do a bit more work
Thread.Sleep(1000);
})
// More commonly, we'll continue a task with a new task on
// the UI thread, since this lets us update when our
// "work" completes.
.ContinueWith(_ => this.label1.Text = "Task Complete!", context);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.