【问题标题】:Task.Continuewith (on current thread)Task.Continuewith(在当前线程上)
【发布时间】:2014-07-01 22:57:28
【问题描述】:

我有一个方法,代码如下:

object frm = null;

// shows the overlay loading mask
Core.ShowLoadingMask("Please wait...");

// start task
Task.Factory.StartNew(() => {

    // go to server and get the data
    var employee = new Data.Entities.Employee(employeeId);

    // instantiate the class type (reflection)
    frm = Activator.CreateInstance(type, employee );

}).ContinueWith((task) => {

    // hide loading mas
    Core.HideLoadingMask();

    if (frm != null) this.Panel.Controls.Add(frm);

});

那么,我怎样才能强制ContinueWith() 中的代码强制使用当前线程,或者我做错了。

我需要的流程是:

  1. 在从服务器获取数据之前显示加载掩码
  2. 从服务器获取数据(可能需要 3 秒)
  3. 然后退出任务并隐藏加载掩码。

有什么线索吗?

【问题讨论】:

    标签: c# winforms task-parallel-library async-await


    【解决方案1】:

    假设this也是一个UI控件,你可以在启动任务之前使用this.Dispatcher存储当前调度器。然后在ContinueWith中,使用存储调度器执行隐藏操作。见Dispatcher.BeginInvoke

    Dispatcher dispatcher = this.Dispatcher;
    
    Core.ShowLoadingMask("Please wait...");
    
    return Task.Factory.StartNew(() =>
    {
        doStuff();
        frm = ...
    }).ContinueWith(t =>
    {
        dispatcher.BeginInvoke(new Action(() =>
        {
            Core.HideLoadingMask();
            if (frm != null) this.Panel.Controls.Add(frm);
        }));
    });
    

    【讨论】:

      【解决方案2】:

      TaskScheduler.FromCurrentSynchronizationContext() 传递给ContinueWith()...

      .ContinueWith((task) => {
          // hide loading mas
          Core.HideLoadingMask();
      
          if (frm != null) this.Panel.Controls.Add(frm);
      }, TaskScheduler.FromCurrentSynchronizationContext());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多