Task.Factory.StartNew vs Task.Factory.FromAsync

前端 未结 2 1541
挽巷
挽巷 2021-01-30 02:07

Let\'s suppose we have a I/O bound method (such as a method making DB calls). This method can be run both in synchronously and asynchronously. That is,

  1. Sync:

2条回答
  •  花落未央
    2021-01-30 02:48

    (1) will (likely) cause the .NET thread pool to process your Task.

    (2) will use whatever mechanism your BeginIOMethod / EndIOMethod pair natively uses to handle the asynchronous part, which may or may not involve the .NET thread pool.

    For example, if your BeginIOMethod is sending a TCP message across the internet, and at a later time the recipient is going to send you a TCP message in response (received by EndIOMethod), then the asynchronous nature of the operation is not being provided by the .NET thread pool. The TCP library being used is providing the asynchronous part.

    This can be accomplished by using the TaskCompletionSource class. Task.Factory.FromAsync can create a TaskCompletionSource, return its Task, then use EndIOMethod as a trigger to place the Result into the Task that was returned form Task.Factory.FromAsync at the time of calling.

    What's the performance difference in terms of the resource utilization?

    The difference between (1) and (2) is primarily just whether the .NET thread pool is going to have its workload added to or not. In general, the correct thing to do is to choose Task.Factory.FromAsync if you only have a Begin... / End... pair and Task.Factory.StartNew otherwise.


    If you're using C# 5.0, then you should be using the non-blocking await task; instead of task.Wait();. (See svick's answer.)

提交回复
热议问题