Task.Continuewith(在当前线程上)

时间:2014-05-14 03:50:13

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

我有一个方法,包含以下代码:

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. 然后退出任务并隐藏加载掩码。
  4. 有任何线索吗?

2 个答案:

答案 0 :(得分:6)

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

.ContinueWith((task) => {
    // hide loading mas
    Core.HideLoadingMask();

    if (frm != null) this.Panel.Controls.Add(frm);
}, TaskScheduler.FromCurrentSynchronizationContext());

答案 1 :(得分: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);
    }));
});