C# 异步&;等待IL码
如果我实现默认的异步/等待方法,如:C# 异步&;等待IL码,c#,async-await,C#,Async Await,如果我实现默认的异步/等待方法,如: class Program { static void Main(string[] args) { new Program().TestMethod(); } private async void TestMethod() { await Task.Delay(10); } } 生成的IL代码和异步状态机包含一个字段“this”,其中引用了调用该方法的实例。如果将代码调整为静
class Program
{
static void Main(string[] args)
{
new Program().TestMethod();
}
private async void TestMethod()
{
await Task.Delay(10);
}
}
生成的IL代码和异步状态机包含一个字段“this”,其中引用了调用该方法的实例。如果将代码调整为静态代码,则当然不存在“this”值
不要通过反射来实现这一点,更多的是从CLR或调试器的角度。
有人知道我如何在“静态测试方法”中确定从哪个方法调用我吗?在IL级别
class Program
{
static void Main(string[] args)
{
TestMethod();
}
private static async void TestMethod()
{
await Task.Delay(10);
}
}
如何在“静态TestMethod”中确定从哪个方法调用我
您可以使用属性
static void Main(string[] args)
{
new Program().TestMethod();
Console.ReadLine();
}
private async void TestMethod([CallerMemberName]string caller = "")
{
Console.WriteLine(caller);
}
PS:您也可以使用
调用文件路径
或调用文件编号
您不必等待等待者。您不应该依赖功能的私有实现细节。如果给定的方法需要访问某个特定实例,则应显式公开该实例,以便可靠地访问它,而不是试图查找可能包含或可能不包含所需信息的私有实现详细信息。我不依赖于此,只是想知道CLR是如何跟踪到等待的根的…CLR没有。编译器编写一个状态机将代码转换回calback模式。如何?关于生成的IL状态机的任何文档?
static void Main(string[] args)
{
new Program().TestMethod();
Console.ReadLine();
}
private async void TestMethod([CallerMemberName]string caller = "")
{
Console.WriteLine(caller);
}