任务在UI线程延续 [英] Task continuation on UI thread

查看:102
本文介绍了任务在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());

这是适用于仅在当前执行上下文是在UI线程上。

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());

This is suitable only if the current execution context is on the UI thread.

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

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