【问题标题】:Task continuation on UI thread, when started from background thread从后台线程启动时,UI 线程上的任务继续
【发布时间】:2012-05-15 18:00:02
【问题描述】:

如果以下代码在后台线程上运行,我如何在主线程上'ContinueWith'?

  var task = Task.Factory.StartNew(() => Whatever());
  task.ContinueWith(NeedThisMethodToBeOnUiThread), TaskScheduler.FromCurrentSynchronizationContext())

上面的不行,因为当前的同步上下文已经是后台线程了。

【问题讨论】:

    标签: c# c#-4.0 parallel-processing task-parallel-library


    【解决方案1】:

    您需要从 UI 线程获取对 TaskScheduler.FromCurrentSynchronizationContext() 的引用并将其传递给延续。

    与此类似。 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);
    }
    

    【讨论】:

    • 我害怕那个。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2015-01-12
    • 2023-01-30
    • 2015-12-09
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多