我知道在主线程上有一个类似的问题:ContinueWith a Task on the Main thread
但这个问题更多的是针对 wpf,我无法让它在控制台应用程序上运行。
我想在不同的线程上执行一个方法,当该方法完成后,我想继续在主线程上执行。我不想加入方法。无论如何,这就是我所拥有的:
class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.Name = "MAIN";
DoWork(x =>
{
Console.Write("Method successfully executed. Executing callback method in thread:" +
"\n" + Thread.CurrentThread.Name);
});
Console.Read();
}
static void DoWork(Action<bool> onCompleteCallback)
{
Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing
Task doWork = new Task(() =>
{
Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing
Thread.Sleep(4000);
});
Action<Task> onComplete = (task) =>
{
onCompleteCallback(true);
};
doWork.Start();
// this line gives an error!
doWork.ContinueWith(onComplete, TaskScheduler.FromCurrentSynchronizationContext());
}
}
如何在主线程上执行 onCompleteCallback 方法?