如果我将使用 TaskFactory.StartNew(MyFunc(), new CancellationToken(), TaskCreationOptions.None, TaskScheduler.Current) 会怎样?
对于 TaskScheduler.Current,它会同步执行 MyFunc() 还是使用一些随机线程,或者其他什么?
请您参考如下方法:
With TaskScheduler.Current will it just synchronous execute MyFunc() or use some random thread, or something else?
这取决于执行范围以及Current 的值是多少。尽管极不可能同步执行此操作。即使使用UI同步上下文,也会使用BeginInvoke异步发布,但它会发布到 UI 线程。
关于Current的值,the docs say :
When not called from within a task, Current will return the Default scheduler.
如果你从另一个 Task 执行这段代码,你传递了另一个 TaskScheduler,那么 Current 的值就是那就是你的代表将被运行的地方。例如,如果 TaskScheduler.FromCurrentSynchronizationContext 是从 UI 线程捕获的,您最终会将此委托(delegate)发布到 UI 消息循环。否则,它将使用 Default,即 ThreadPoolTaskScheduler,然后您的委托(delegate)将在任意线程池线程上被调用。
