異步
class Program
{
static void Main(string[] args)
{
callMethod();
Console.ReadKey();
}
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 += 1;
}
});
return count;
}
public static void Method2()
{
for (int i = 0; i < 25; i++)
{
Console.WriteLine(" Method 2");
}
}
public static void Method3(int count)
{
Console.WriteLine("Total count is " + count);
}
}
通過await等待method3的執(zhí)行結(jié)果,最后輸出
image003.jpg
再來看一個(gè)實(shí)際的例子
class Program
{
static void Main()
{
Task task = new Task(CallMethod);
task.Start();
task.Wait();
Console.ReadLine();
}
static async void CallMethod()
{
string filePath = "E:\\sampleFile.txt";
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 stating");
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;
}
}
主Task會(huì)在遇到await后等待Task的執(zhí)行結(jié)果,然后再執(zhí)行后面的代碼,所以得到結(jié)果
image004.jpg
再來看Generic host中的異步
class Program
{
static async Task Main(string[] args)
{
await CreateHostBuilder(args).Build().RunAsync();
}
private static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Loop250ms>();
services.AddHostedService<Run5sec>();
});
}
}
在這里注冊(cè)了Loop250ms和Run5sec兩個(gè)服務(wù)
public class Loop250ms : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("Loop250ms.ExecuteAsync");
while(!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("(loop)");
await Task.Delay(250);
}
Console.WriteLine("Loop250ms.ExecuteAsync Cancelled");
}
}
每250ms輸出一次(loop)
public class Run5sec:BackgroundService
{
private readonly IHostApplicationLifetime applifetime;
public Run5sec(IHostApplicationLifetime applifetime)
{
this.applifetime = applifetime;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("Tick1000ms.ExecuteAsync");
for (int i = 5; i > 0;i--)
{
if(stoppingToken.IsCancellationRequested) break;
Console.WriteLine($"tick {i}");
await Task.Delay(1000);
}
Console.WriteLine("Tick1000ms calling StopApplication");
applifetime.StopApplication();
}
}
倒計(jì)時(shí)5秒,倒計(jì)時(shí)完成時(shí)調(diào)用applifetime.StopApplication結(jié)束應(yīng)用
輸出結(jié)果
image.png
可以看到兩個(gè)服務(wù)互不影響的執(zhí)行,直到applifetime.StopApplication被調(diào)用,應(yīng)用程序向Loop250ms中傳入CancellationToken(的確是這樣嗎,我也不清楚,求大佬解答)