C#Async,await异步简单介绍
2021-06-10 05:06
标签:task fse pac can ext ken eth ring contain C# 5.0 引入了async/await,.net framework4.5开始支持该用法 使用: 由async标识的方法必须带有await,如果不带await,方法将被同步执行 运行结果: 结果说明: 只有执行到Task异步的时候,才使真正的异步 微软的例子: 查看ReadToEndAsync源码,发现最后是TaskFactory C#Async,await异步简单介绍 标签:task fse pac can ext ken eth ring contain 原文地址:https://www.cnblogs.com/yaosj/p/10623081.html static void Main(string[] args)
{
fun22();
Console.WriteLine($"Main await ThreadId {Thread.CurrentThread.ManagedThreadId}");
Console.ReadKey();
}
private async static void fun22()
{
//sync同步(相对于调用函数的线程)
Console.WriteLine($"pre await ThreadId {Thread.CurrentThread.ManagedThreadId}");
await HelloWorld();
//async异步(相对于调用函数的线程)
Console.WriteLine($"after await ThreadId {Thread.CurrentThread.ManagedThreadId}");
}
private static Task HelloWorld()
{
//sync同步(相对于调用函数的线程)
Console.WriteLine($"pre Task ThreadId {Thread.CurrentThread.ManagedThreadId}");
//async异步(相对于调用函数的线程)
return Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
Console.WriteLine($"Task ThreadId {Thread.CurrentThread.ManagedThreadId}");
});
}
using System;
using System.IO;
namespace ConsoleApplication
{
class Program
{
static async Task Main()
{
await ReadCharacters();
}
static async Task ReadCharacters()
{
String result;
using (StreamReader reader = File.OpenText("existingfile.txt"))
{
Console.WriteLine("Opened file.");
result = await reader.ReadToEndAsync();
Console.WriteLine("Contains: " + result);
}
}
}
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task