I have something like this:
private void DoSomething()
{
System.Console.WriteLine("Creating Foo");
Foo result = new Foo();
DoSomethingAsync();
System.Console.WriteLine("Returning Foo");
return result;
}
private async void DoSomethingAsync()
{
// The following task takes a long time, but is not CPU intensive
await TaskEx.Run(() =>
{
// code lives here... removed for this example
});
}
Since I don’t hit the CPU much, I don’t need a thread. What can I use instead of Run to avoid the creation of a thread?
I think you’re misunderstanding the intent of the Task Asynchrony Pattern here. What you’re doing is probably better handled by
ThreadPool.QueueUserWorkItemwhich will reuse a worker thread from the process’s pool, only creating one if necessary.The TAP allows you to break a task into “chunks” of work that can be processed incrementally, but it does not directly provide a means to say “this is a background task”.