下面的程序使用了一般的Task.Run(),以及使用async和await(异步)方式。在两种情况下,都会从线程池中获取一个不同的线程用于新任务。那么,它们有什么区别呢?异步意味着它应该使用主线程并在任务完成之前释放它。但它也使用了另一个线程而不是主线程。
public class Worker2
{
public bool IsComplete { get; private set; }
internal void DoWork()
{
this.IsComplete = false;
Console.WriteLine("Doing Work.");
Task.Run(new Action(LongOperation));
Console.WriteLine("Work Completed");
IsComplete = true;
}
private void LongOperation()
{
Console.WriteLine("long operation thread thread :" + Thread.CurrentThread.ManagedThreadId);//Thread Id = 7. it is different from main thread id.
Console.WriteLine("Working!");
Thread.Sleep(3000);
}
}
//并且是异步的
public class Worker2
{
public bool IsComplete { get; private set; }
internal async void DoWork()
{
this.IsComplete = false;
Console.WriteLine("Doing Work.");
await LongOperation();
Console.WriteLine("Work Completed");
IsComplete = true;
}
private Task LongOperation()
{
return Task.Run(() =>
{
Console.WriteLine("long operation thread thread :" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Working!");
Thread.Sleep(3000);
});
}
}