c# - 从 QueueUserWorkItem 移动到任务

标签 c# task-parallel-library task

.NET 4.5 和 VS2012 是我的目标

在我的 C# 中,我有很多这样的旧代码:

var stuff;
ThreadPool.QueueUserWorkItem(() =>
    {
          stuff=GetStuff():
           InvokeOnMainThread(stuff);
    });

这是如何使用 C# 中的新任务系统完成的?

最佳答案

这通常映射到:

Task.Factory.StartNew(() =>
{
     return GetStuff():                  
}).ContinueWith(t =>
{
    // InvokeOnMainThread(t.Result); // Note that this doesn't need to "Invoke" now
    UseStuff(t.Result); 
}, TaskScheduler.FromCurrentSynchronizationContext()); // Moves to main thread

如果您使用的是 Visual Studio 2012 和 .NET 4.5,您还可以选择将方法标记为 async,然后执行以下操作:

var stuff = await Task.Run(() => GetStuff());
UseStuff(stuff); // Will be on the main thread here...

关于c# - 从 QueueUserWorkItem 移动到任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19500778/

相关文章:

c# - 多任务延续

c# - 使用 .FromAsync 任务状态 = WaitingForActivation

c# - Entity Framework 数据库优先,同表名和列名映射

c# - Unity3D Kudan SDK无标记增强现实帮助指导

c# - 什么是 "static"类?

c# - 为什么我应该更喜欢使用 API 异步函数而不是用 Task.Run 包装同步函数?

c# - 带有 TaskCompletionSource 的 TaskCreationOptions 的目的是什么?

powershell - 在 powershell 中并行运行任务

c# - 将 ListBox 放入 ScrollViewer : mouse wheel does not work