Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 469
Jake Avatar asked Feb 28 '13 19:02

Jake


1 Answers

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.)

like image 133
Jon Skeet Avatar answered Nov 13 '22 09:11

Jon Skeet