var task = Task.Factory.StartNew(() => { IOMethod(); });
task.Wait();
这将阻塞线程池线程IOMethod()
正在执行,并且还阻塞当前线程,因为Wait()
。阻塞线程总数:2。
var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ... );
task.Wait();
这将(很可能)在不使用线程的情况下异步执行操作,但它会阻塞当前线程,因为Wait()
。阻塞线程总数:1。
IOMethod();
这将阻塞当前线程IOMethod()
正在执行。阻塞线程总数:1。
如果您需要阻止当前线程,或者如果阻止它对您来说没问题,那么您应该使用它,因为尝试使用 TPL 实际上不会给您任何东西。
var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ... );
await task;
这将在不使用线程的情况下异步执行操作,并且还将等待操作异步完成,这要归功于await
。阻塞线程总数:0。
如果您想利用异步并且可以使用 C# 5.0,则应该使用此方法。
var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ... );
task.ContinueWith(() => /* rest of the method here */);
这将在不使用线程的情况下异步执行操作,并且还将等待操作异步完成,这要归功于ContinueWith()
。阻塞线程总数:0。
如果您想利用异步性并且无法使用 C# 5.0,则应该使用此方法。