await/async:是由.net4.5引入的语法糖。(由编译器提供的便捷功能就是语法糖)
await/async语法:
1.)async 是用来修饰方法,如果单独出现,方法会警告,没有什么作用;
2.)await在方法体内部,只能放在async修饰的方法内,必须放在task前面;
3.)async/await方法里面如果没有返回值,默认返回一个Task,或者void(推荐用Task,而不是void,因为这样才能await/wait);
4.)带async+await后,返回值要多一层Task<>;
1.使用Task,Async,Sync读取文件各个需要耗时时间:
#region ReadFile
public static void Show()
{
{
Console.WriteLine("******************ReadFile***************");
string path = "D:\\ceshi\\ceshi.zip";
int loopNum = 10;//30
{
Console.WriteLine("*****************Async****************");
List<Task> taskList = new List<Task>();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < loopNum; i++)
{
taskList.Add(ReadAsync(path, i));
}
Task.WaitAll(taskList.ToArray());
stopwatch.Stop();
Console.WriteLine($"Async耗时{stopwatch.ElapsedMilliseconds}ms,ThreadId={Thread.CurrentThread.ManagedThreadId}")
}
Thread.Sleep(3000);
{
Console.WriteLine("*****************Task****************");
List<Task> taskList = new List<Task>();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < loopNum; i++)
{
taskList.Add(ReadTask(path, i));
}
Task.WaitAll(taskList.ToArray());
stopwatch.Stop();
Console.WriteLine($"Task耗时{stopwatch.ElapsedMilliseconds}ms,ThreadId={Thread.CurrentThread.ManagedThreadId}");
}
Thread.Sleep(3000);
{
Console.WriteLine("*****************Sync****************");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < loopNum; i++)
{
ReadSync(path, i);
}
stopwatch.Stop();
Console.WriteLine($"Sync耗时{stopwatch.ElapsedMilliseconds}ms,ThreadId={Thread.CurrentThread.ManagedThreadId}");
}
}
#endregion
#region Read
private static async Task<byte[]> ReadAsync(string path, int num)
{
Console.WriteLine($"This is ReadAsync{num} Start,ThreadId={Thread.CurrentThread.ManagedThreadId}");
var result = await File.ReadAllBytesAsync(path);
Console.WriteLine($"This is ReadAsync{num} End,ThreadId={Thread.CurrentThread.ManagedThreadId}");
return result;
}
private static Task<byte[]> ReadTask(string path, int num)
{
Console.WriteLine($"This is ReadTask{num} Start,ThreadId={Thread.CurrentThread.ManagedThreadId}");
var result = Task.Run(() =>
{
Console.WriteLine($"This is ReadTask Ing,ThreadId={Thread.CurrentThread.ManagedThreadId}");
return File.ReadAllBytes(path);
});
Console.WriteLine($"This is ReadTask{num} End,ThreadId={Thread.CurrentThread.ManagedThreadId}");
return result;
}
private static byte[] ReadSync(string path, int num)
{
Console.WriteLine($"This is ReadSync{num} Start,ThreadId={Thread.CurrentThread.ManagedThreadId}");
var result = File.ReadAllBytes(path);
Console.WriteLine($"This is ReadSync{num} End,ThreadId={Thread.CurrentThread.ManagedThreadId}");
return result;
}
#endregion
从上面的代码可以看到Async在读取方法是调用的是“File.ReadAllBytesAsync”方法,而该方法大致采用DMA技术,而该技术实现原理是,硬盘接受命令后,CPU继续执行自己的线程,当硬盘中“读/写”自己操作完毕后会发中断信号,CPU会继续处理,而这中间就是基于DMA异步操作,从而节省CPU资源。
2.适用场景
1.)跟第三方交互(非托管资源,Async版本)
2.)数据库OpenAsync
3.)Redis
4.)Web请求
5.)文件读取