1.前言
众所周知,C#里面的等待异步执行一般都是用async/await。这个东西的IL代码长篇大论,看着很丑陋的那种。
public static async void ABC()
{
await Task.Run(() =>
{
Console.WriteLine("Call ABC");
});
}
IL代码:
.custom instance void [System.Runtime]System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 1E 44 6E 47 75 61 72 64 5F 54 65 73 74 2E // ...Test.
50 72 6F 67 72 61 6D 2B 3C 44 45 46 3E 64 5F 5F // Program+<DEF>d__ 30 00 00 ) // 0..
.custom instance void [System.Runtime]System.Diagnostics.DebuggerStepThroughAttribute::.ctor() = ( 01 00 00 00 )
// 代码大小 38 (0x26)
.maxstack 2
.locals init (class Test.Program/'<DEF>d__0' V_0)
IL_0000: newobj instance void Test.Program/'<DEF>d__0'::.ctor()
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call valuetype [System.Runtime]System.Runtime.CompilerServices.AsyncVoidMethodBuilder [System.Runtime]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::Create()
IL_000c: stfld valuetype [System.Runtime]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.Program/'<DEF>d__0'::'<>t__builder'
IL_0011: ldloc.0
IL_0012: ldc.i4.m1
IL_0013: stfld int32 Test.Program/'<DEF>d__0'::'<>1__state'
IL_0018: ldloc.0
IL_0019: ldflda valuetype [System.Runtime]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.Program/'<DEF>d__0'::'<>t__builder'
IL_001e: ldloca.s V_0
IL_0020: call instance void [System.Runtime]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::Start<class Test.Program/'<DEF>d__0'>(!!0&)
IL_0025: ret
} // end of method Program::DEF
C++是怎么实现异步等待的呢?
2.代码
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
int i = 0;
while(i < 20)
{
printf(" I am from a thread, count = %d \n", i++);
}
return 0;
}
int main(int argc, char* argv[])
{
HANDLE hThread;
DWORD dwThreadId;
// 创建一个线程
hThread = ::CreateThread (
NULL, // 默认安全属性
NULL, // 默认堆栈大小
ThreadProc, // 线程入口地址(执行线程的函数)
NULL, // 传给函数的参数
0, // 指定线程立即运行
&dwThreadId); // 返回线程的ID号
printf(" Now another thread has been created. ID = %d \n", dwThreadId);
// 等待新线程运行结束
::WaitForSingleObject (hThread, INFINITE);
::CloseHandle (hThread);
return 0;
}
C++里面用一个WaitForSingleObject函数即可等待异步完成。它的第一个参数受信或者第二个参数的时间超时,它就不再等待了。所见即所得,看起来也清爽很多。