C# 异步编程
关于“同步”和“异步”介绍可以先看这篇文章:真的理解同步和异步了吗?
使用Task对象来实现多线程async/async方式异步编程:
public class Program
{
static int i = 0;
static void Main(string[] args)
{
Console.WriteLine("主线程:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
TestAsycAsync();
i++;
Console.WriteLine("i="+i);
Console.WriteLine("主线程结束:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
Console.ReadKey();
}
public static async Task TestAsycAsync()
{
Console.WriteLine("当前线程是:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
i = await GetReturnResult();
Console.WriteLine("i=" + i);
Console.WriteLine("当前线程是:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
}
static async Task<int> GetReturnResult()
{
Console.WriteLine("当前线程是:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
//异步开始
int s = await Task.Run(() =>
{
Console.WriteLine("当前线程是:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
Thread.Sleep(3000); //睡眠3s
i++;
return i;
});
return s;
}
}
执行顺序:
蓝色标记是主线程,红色标记为异步线程,可以看到当主线执行到await之前程序都是正常运行,在遇到await时,主线程在此方法运行结束,回到原调用的地方,异步线程开始与主线程同时执行。