是否有一种"标准"方式来指定任务延续应该在创建初始任务的线程上运行?
目前我有下面的代码 - 它正在工作,但跟踪调度程序和创建第二个动作似乎是不必要的开销.
dispatcher = Dispatcher.CurrentDispatcher;
Task task = Task.Factory.StartNew(() =>
{
DoLongRunningWork();
});
Task UITask= task.ContinueWith(() =>
{
dispatcher.Invoke(new Action(() =>
{
this.TextBlock1.Text = "Complete";
}
});
Run Code Online (Sandbox Code Playgroud) 我正在使用Tasks在我的ViewModel中运行长时间运行的服务器调用,结果将被重新编组Dispatcher使用TaskScheduler.FromSyncronizationContext().例如:
var context = TaskScheduler.FromCurrentSynchronizationContext();
this.Message = "Loading...";
Task task = Task.Factory.StartNew(() => { ... })
.ContinueWith(x => this.Message = "Completed"
, context);
Run Code Online (Sandbox Code Playgroud)
这在我执行应用程序时工作正常.但是当我运行我的NUnit测试时,Resharper我在调用时收到错误消息FromCurrentSynchronizationContext:
当前的SynchronizationContext可能不会用作TaskScheduler.
我想这是因为测试是在工作线程上运行的.如何确保测试在主线程上运行?欢迎任何其他建议.
我想写一个Promise/Deffered模式.完美的变体到底是:
MyObject().CallMethodReturningPromise()
.done( result => {
...something doing;
} )
.fail( error => {
...error handle;
} )
.always( () => {
...some code;
} )
Run Code Online (Sandbox Code Playgroud)
我发现了这个实现https://bitbucket.org/mattkotsenas/c-promises/overview和https://gist.github.com/cuppster/3612000.但是我怎么能用它来解决我的任务?
.NET 是否在新的不同线程池线程上恢复等待继续,还是重用先前恢复的线程?
让我们在下面的 .NET Core 控制台应用程序中的 C# 代码中想象一下:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NetCoreResume
{
class Program
{
static async Task AsyncThree()
{
await Task.Run(() =>
{
Console.WriteLine($"AsyncThree Task.Run thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
});
Console.WriteLine($"AsyncThree continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
}
static async Task AsyncTwo()
{
await AsyncThree();
Console.WriteLine($"AsyncTwo continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
}
static async Task AsyncOne()
{
await AsyncTwo();
Console.WriteLine($"AsyncOne continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
}
static void Main(string[] args)
{
AsyncOne().Wait();
Console.WriteLine("Press any key to end...");
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
它会输出:
AsyncThree …Run Code Online (Sandbox Code Playgroud)