c# - Task.Continuewith(在当前线程上)

标签 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. 然后退出任务并隐藏加载掩码。

有什么线索吗?

最佳答案

通过 TaskScheduler.FromCurrentSynchronizationContext()ContinueWith()...

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

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

关于c# - Task.Continuewith(在当前线程上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23645302/

相关文章:

c# - 为什么在取消之前不等待任务?

c# - 一起运行两个 parallel.foreach()

c# - 匿名并行任务计时器?

c# - 设置 TCP/IP 客户端和服务器以通过网络进行通信

c# - 如何将数据从 Microsoft Access 传输到 SQL Server 2008?

c# - 无法正则表达式替换

c# - 如何使用 C# 设置 azure 中继混合连接以连接到本地 SQL Server?

c# - Windows 窗体 - 奇怪的自动滚动行为

winforms - 允许每个项目在 Winforms 组合框(或列表框)中使用多行

c# - 这种强制不变性的模式有什么缺点?