.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/