且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Task.Factory.StartNew VS Task.Factory.FromAsync

更新时间:2023-10-26 20:31:04

  VAR任务= Task.Factory.StartNew(()=> {IOMethod();});
task.Wait();
 

这将阻止线程池线程,而 IOMethod()正在执行,并阻止,因为等待()$您的当前线程C $ C>。总阻塞的线程:2

  VAR任务= Task.Factory.FromAsync(BeginIOMethod,EndIOMethod,...);
task.Wait();
 

这将(最有可能)执行异步操作,而无需使用一个线程,但它会阻塞,因为当前线程的等待()。总阻塞的线程:1。

  IOMethod();
 

这将阻止执行当前线程,而 IOMethod()。总阻塞的线程:1。

如果您需要阻止当前线程,或者阻塞它是好的你,那么你应该使用这个,因为尝试使用第三方物流实际上不会给你任何东西。

  VAR任务= Task.Factory.FromAsync(BeginIOMethod,EndIOMethod,...);
等待任务;
 

这将异步执行的操作,而无需使用一个线程,它也将等待操作异步完成,这要归功于等待。总阻塞的线程:0

这是你应该使用什么,如果你想充分利用异步的,你可以使用C#5.0。

  VAR任务= Task.Factory.FromAsync(BeginIOMethod,EndIOMethod,...);
task.ContinueWith(()=> / *休息的方法,在这里* /);
 

这将异步执行的操作,而无需使用一个线程,它也将等待操作异步完成,这要归功于 ContinueWith()。总阻塞的线程:0

这是你应该使用什么,如果你想充分利用异步的,你不能使用C#5.0。

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:

    IOMethod()
    

  2. Async:

    BeginIOMethod()
    EndIOMethod()
    

Then when we execute the method in different ways as shown below, what's the performance difference in terms of the resource utilization?

  1. var task = Task.Factory.StartNew(() => { IOMethod(); });
    task.Wait();
    

  2. var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ... );
    task.Wait();
    

var task = Task.Factory.StartNew(() => { IOMethod(); });
task.Wait();

This will block a thread pool thread while IOMethod() is executing and also block your current thread because of the Wait(). Total blocked threads: 2.

var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ... );
task.Wait();

This will (most likely) perform the operation asynchronously without using a thread, but it will block the current thread because of the Wait(). Total blocked threads: 1.

IOMethod();

This will block the current thread while IOMethod() is executing. Total blocked threads: 1.

If your need to block the current thread, or if blocking it is okay for you, then you should use this, because trying to use TPL won't actually give you anything.

var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ... );
await task;

This will perform the operation asynchronously without using a thread, and it will also wait for the operation to complete asynchronously, thanks to await. Total blocked threads: 0.

This is what you should use if you want to take advantage of asynchrony and you can use C# 5.0.

var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ... );
task.ContinueWith(() => /* rest of the method here */);

This will perform the operation asynchronously without using a thread, and it will also wait for the operation to complete asynchronously, thanks to ContinueWith(). Total blocked threads: 0.

This is what you should use if you want to take advantage of asynchrony and you can't use C# 5.0.