TaskFactory.StartNew 行为
TaskFactory.StartNew behavior
如果我使用 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
异步post,但是会post到UI线程.
关于Current
的价值,the docs say:
When not called from within a task, Current will return the Default
scheduler.
如果您从另一个 Task
执行此代码,您传递了另一个 TaskScheduler
,那将是 Current
的值,这就是您的委托所在的位置运行。例如,如果 TaskScheduler.FromCurrentSynchronizationContext
是从 UI 线程捕获的,您最终会将此委托发布到 UI 消息循环。否则,它将使用 Default
,即 ThreadPoolTaskScheduler
,然后您的委托将在任意线程池线程上被调用。
如果我使用 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
异步post,但是会post到UI线程.
关于Current
的价值,the docs say:
When not called from within a task, Current will return the Default scheduler.
如果您从另一个 Task
执行此代码,您传递了另一个 TaskScheduler
,那将是 Current
的值,这就是您的委托所在的位置运行。例如,如果 TaskScheduler.FromCurrentSynchronizationContext
是从 UI 线程捕获的,您最终会将此委托发布到 UI 消息循环。否则,它将使用 Default
,即 ThreadPoolTaskScheduler
,然后您的委托将在任意线程池线程上被调用。