Task.ContinueWith(在当前线程上)

4

我有一个带以下代码的方法:

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. 在此之后退出任务,并隐藏加载遮罩。

有什么线索吗?

2个回答

8
TaskScheduler.FromCurrentSynchronizationContext() 传递给 ContinueWith()...
.ContinueWith((task) => {
    // hide loading mas
    Core.HideLoadingMask();

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接