请有人能够确认我是否正确理解了Async await关键字吗?(使用CTP的第3版)
到目前为止,我已经解决了在方法调用之前插入await关键字基本上做了两件事,A.它创建一个立即返回和B.它创建一个"延续",在完成异步方法调用时调用.在任何情况下,continuation都是该方法的代码块的其余部分.
所以我想知道的是,这两位代码在技术上是等价的,如果是这样,这基本上意味着await关键字与创建ContinueWith Lambda相同(即:它基本上是一个编译器快捷方式)?如果没有,有什么区别?
bool Success =
await new POP3Connector(
"mail.server.com", txtUsername.Text, txtPassword.Text).Connect();
// At this point the method will return and following code will
// only be invoked when the operation is complete(?)
MessageBox.Show(Success ? "Logged In" : "Wrong password");
Run Code Online (Sandbox Code Playgroud)
VS
(new POP3Connector(
"mail.server.com", txtUsername.Text, txtPassword.Text ).Connect())
.ContinueWith((success) =>
MessageBox.Show(success.Result ? "Logged In" : "Wrong password"));
Run Code Online (Sandbox Code Playgroud) 我似乎遇到了C#编译器的一些奇怪行为.
请考虑以下代码示例:
static void Main(string[] args)
{
Foo(false, 8);
}
public static void Foo(bool execute, int x)
{
if (execute)
{
Task.Run(() => Console.WriteLine(x));
}
}
Run Code Online (Sandbox Code Playgroud)
运行此(在发布中)显示发生了一些意外的分配.检查IL表明闭包触发的堆分配出现在函数的最开头,而不是在条件内:
.method public hidebysig static void
Foo(
bool execute,
int32 x
) cil managed
{
.maxstack 2
.locals init (
[0] class Test.Program/'<>c__DisplayClass1_0' 'CS$<>8__locals0'
)
IL_0000: newobj instance void Test.Program/'<>c__DisplayClass1_0'::.ctor()
IL_0005: stloc.0 // 'CS$<>8__locals0'
IL_0006: ldloc.0 // 'CS$<>8__locals0'
IL_0007: ldarg.1 // x
IL_0008: stfld int32 Test.Program/'<>c__DisplayClass1_0'::x
// [18 13 - 18 25]
IL_000d: ldarg.0 …Run Code Online (Sandbox Code Playgroud)