The new async language features in c# 5.0 rely heavily on the Task object, and lots of examples show that one common way to run some of your code in a Task is to start it via Task.Run(), which represents your code as a Task and runs it on a threadpool thread.
However, I also have read that one should not start long-running code on the threadpool threads, which leads me to this question: is it possible to still use all the C# async language features (such as Task, ‘await’, ‘async’) on “regular” threads and not use the threadpool? In this case, how would one get a Task object representing code running on a “regular” thread?
And as a follow up question about the rule of not running long-running code in the threadpool – is this rule only about code that is cpu intensive? What if your code runs a long time (72 hours, for example) but spends most of its time doing things like “await Task.Delay()”.. is it then okay to use threadpool threads, or should one use “regular” threads in all cases where your concurrent code needs to run for a long time?
The thread pool will respond to long-running code correctly, so it’s not like you can’t do it – it’s just not the most efficient way to do it.
Also note that
Task.Delayimplies the opposite of “long-running” – the individualTaskactually completes at the point of theawaitand is no longer on the thread pool. AnotherTaskis created and queued to the thread pool whenTask.Delaycompletes. TheTaskreturned byTask.Run(when you pass it anasyncdelegate) is actually a “proxyTask” that represents the entire delegate.In your situation, you don’t need it, but it is possible. My AsyncEx library includes an
AsyncContextThreadtype that exposes aTaskFactoryproperty you can use to startTasks on that thread.In your case, you don’t need
Task.Runor aTaskFactoryat all. You can easily do this in parallel without explicitly sending work off to the thread pool: