- 通过async/await这两个关键字编写出来的代码,代码长(zhang)的像同步编程,但实际上是异步编程。也就是说,async/await能够以同步编程的形式实现异步编程。
- async/await是C#5.0引入的。
- 关键字async用在方法定义前面,关键字await只能用在async标记的方法中。
- async修饰的方法的返回值类型只能是void或者Task或者Task<T>这三种类型,且方法的参数能用ref/out修饰。
- await异步等待的地方,await后面的代码和前面的代码执行的线程可能不一样(取决于await时任务是否完成)。
参考资料:
https://www.cnblogs.com/liqingwen/p/5831951.html#!comments
https://www.c-sharpcorner.com/article/async-and-await-in-c-sharp/
以下为本人调试时的代码:
代码1:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace 简单用法
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 主线程ThreadId = " + Thread.CurrentThread.ManagedThreadId);
AsyncTest();
Console.ReadLine();
}
static Task<int> Print()
{
var tcs = new TaskCompletionSource<int>();
var thread = new Task(() =>
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 子线程Id = " + Thread.CurrentThread.ManagedThreadId);
for (int i = 0; i < 3; i++)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " =====等待===== " + i);
Thread.Sleep(1000);
}
tcs.SetResult(99);
});
thread.Start();
return tcs.Task;
}
async static void AsyncTest()
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " *****Start***** ThreadId = " + Thread.CurrentThread.ManagedThreadId);
Task<int> taskA = Print();
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " *****Middle***** ThreadId = " + Thread.CurrentThread.ManagedThreadId);
await taskA;//await后面的代码和前面的代码执行的而线程可能不一样(这个应该是涉及“出让执行权”)
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "*****End***** ThreadId = " + Thread.CurrentThread.ManagedThreadId);
}
}
}
运行结果:
代码2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//In this example,we are going to take two methods,
//which are not dependent on each other.
namespace 简单用法2
{
class Program
{
static void Main(string[] args)
{
Method1();
Method2();
Console.ReadLine();
}
public static async Task Method1()
{
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(" Method 1 ");
Thread.Sleep(100);
}
});
}
public static void Method2()
{
for (int i = 0; i < 25; i++)
{
Console.WriteLine(" Method 2 ");
Thread.Sleep(500);
}
}
}
}
运行结果:
代码3:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//In this example,Method1 is retirning total length as an integer value and we are passing a parameter
//as a length in a Method3,Which is coming from Method1.
namespace 简单用法3
{
class Program
{
static void Main(string[] args)
{
callMethod();
Console.ReadLine();
}
public static async void callMethod()
{
Task<int> task = Method1();
Method2();
int count = await task;
Method3(count);
}
public static async Task<int> Method1()
{
int count = 0;
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(" Method 1 ");
count++;
Thread.Sleep(100);
}
});
return count;
}
public static void Method2()
{
for (int i = 0; i < 25; i++)
{
Console.WriteLine(" Method 2 ");
Thread.Sleep(200);
}
}
public static void Method3(int count)
{
Console.WriteLine("Total count is " + count);
}
}
}
运行结果:
代码4:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//In this example,we are going to read all the character from a
//large text file asynchronously and get the total length of all the characters.
namespace 简单用法4
{
class Program
{
static void Main(string[] args)
{
Task task = new Task(CallMethod);
task.Start();
task.Wait();
Console.ReadLine();
}
static async void CallMethod()
{
string filePath = @"C:\Io.dos";
Task<int> task = ReadFile(filePath);
Console.WriteLine(" other work 1");
Console.WriteLine(" other work 2");
Console.WriteLine(" other work 3");
int length = await task;
Console.WriteLine(" Total length = " + length);
Console.WriteLine(" After work 1");
Console.WriteLine(" After work 2");
}
static async Task<int> ReadFile(string file)
{
int length = 0;
Console.WriteLine(" File reading is starting ");
using (StreamReader reader = new StreamReader(file))
{
//Reads all characters from the current position to the end
//of the stream asynchronously and returns them as one string.
string s = await reader.ReadToEndAsync();
length = s.Length;
}
Console.WriteLine(" File reading is completed ");
return length;
}
}
}
运行结果: