Create but not start a task with a custom task factory?

梦想与她 提交于 2020-01-02 02:59:12

问题


I'd like to be able to create a task without starting it, similar to running var a = new Task(); a.Start(); but with a custom factory. Factories provide StartNew(), but I can't find a method to separate the two actions. Is this possible?


回答1:


A TaskFactory is basically two sets of default options (creation and continuation), a default cancellation token, and a task scheduler.

You can specify the cancellation token and the creation options when you just new up a task - and then start it on whatever scheduler you want. So:

Task task = new Task(action,
                     factory.CancellationToken,
                     factory.CreationOptions);
...
task.Start(factory.Scheduler);

should do the job other than continuation options. The continuation options are only relevant when you add a continuation anyway, which you can specify directly. Is there anything which isn't covered by this?

(One thing to note is that the Task-based Asynchronous Pattern generally revolves around "hot" tasks which are started by the time you see them anyway. So you probably want to avoid exposing the unstarted tasks too widely.)



来源:https://stackoverflow.com/questions/15143948/create-but-not-start-a-task-with-a-custom-task-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!