我该如何继续在UI线程任务? [英] How do I continue a Task on the UI thread?

查看:82
本文介绍了我该如何继续在UI线程任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有标准的方式来指定的任务应该继续运行从最初的任务是创建的线程上?

目前我有以下的code - 这是工作,但跟踪调度和创建第二个动作似乎是不必要的开销

 调度= Dispatcher.CurrentDispatcher;
任务task = Task.Factory.StartNew(()=>
{
    DoLongRunningWork();
});

任务UITask = task.ContinueWith(()=>
{
    dispatcher.Invoke(新动作(()=>
    {
        this.TextBlock1.Text =完成;
    }
});
 

解决方案

通话的延续与 TaskScheduler.FromCurrentSynchronizationContext()

 任务UITask = task.ContinueWith(()=>
    {
     this.TextBlock1.Text =完成;
    },TaskScheduler.FromCurrentSynchronizationContext());
 

Is there a 'standard' way to specify that a task continuation should run on the thread from which the initial task was created?

Currently I have the code below - it is working but keeping track of the dispatcher and creating a second Action seems like unnecessary overhead.

dispatcher = Dispatcher.CurrentDispatcher;
Task task = Task.Factory.StartNew(() =>
{
    DoLongRunningWork();
});

Task UITask= task.ContinueWith(() =>
{
    dispatcher.Invoke(new Action(() =>
    {
        this.TextBlock1.Text = "Complete"; 
    }
});

解决方案

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

这篇关于我该如何继续在UI线程任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆