Task.Run without async or await

2019-08-31 05:57发布

问题:

If I put a few of the methods I'm calling, from my controller, into Task.Run what exactly is this doing? I'm not using an async function and I'm not using await.

...
FunctionOne();
FunctionTwo();
return View(FunctionThree().Result);
}

private void FunctionOne()
{
        Task.Run(() =>
        {
            ....
        }
}

private void FunctionTwo()
{
        Task.Run(() =>
        {
            ....
        }
}

private Task<MyType> FunctionThree()
{
        return Task.Run(() =>
        {
            ....
        }
}

回答1:

As @LasseVKarlsen explains, this code attempts to execute functions One, Two and Three in parallel. Task.Run immediately queues the specified work on the thread pool, and .Result will block the calling thread until its Task (and only its task) is complete.

This may or may not be a good design. Some things to consider:

  • You're using four threads from your thread pool to execute this action. If this action is under heavy load -- ie. it's called often -- the number of available threads in your pool could become a new bottleneck.
  • Functions One and Two have an essentially unbounded runtime since no client will be waiting on them. If too much logic is added to those functions, you could again run out of threads in your pool.
  • As @LasseVKarlsen mentions, this may lead to a deadlock.
  • If these are CPU-bound functions, then doing them in parallel may not buy you anything. (However, not waiting on One and Two might buy the client a lot.) If there are I/O operations underneath (eg. network calls, database calls, filesystem calls), you may want to look into Using an Asynchronous Controller in ASP.NET MVC instead.
  • As @StephenCleary notes, ASP.NET doesn't keep track of your threads. If a recycle occurs (say when you edit your web.config), it will always finish function Three as part of the request, but One and Two may be cancelled.

Whether these considerations suggest a change in your design is a question of what each function does, how long they take, and how important they are to your business logic.



标签: c# task