mer*_*tin 4 c# silverlight asynchronous reflection.emit async-await
如何使用反射创建异步方法?
基本上我需要这样的东西:
async public Task asyncmethod()
{
await something();
}
Run Code Online (Sandbox Code Playgroud)
但我需要用反思来做.
async
方法的转换在C#(或VB.NET)编译器级别工作,在CIL中不支持它.编译器在最简单的情况下做的是它翻译代码如下:
async public Task asyncmethod()
{
// some code
var x = await something();
// more code
}
Run Code Online (Sandbox Code Playgroud)
代码基本上等同于:
public Task asyncmethod()
{
// some code
return something().ContinueWith(
t =>
{
var x = t.Result;
// more code
});
}
Run Code Online (Sandbox Code Playgroud)
真正的代码要复杂得多(它使用SynchronizationContext
,如果something()
返回已经完成Task
,它实际上不是异步的,它支持await
其他感谢Task
),对于更复杂的C#代码来说会更复杂.
但是如果你真的想async
使用Reflection.Emit 创建方法,那么这个转换就是你实际需要手动完成的.
但有一点需要注意的是,如果你的方法await
在它之前只使用一次return
,你可以将其重写为(假设something()
返回a Task
而不是其他await
能够的东西):
public Task asyncmethod()
{
// some code
return something();
}
Run Code Online (Sandbox Code Playgroud)