Skip to main content
 首页 » 编程设计

c#之为什么此代码忽略等待并继续进行

2024年02月13日11虾米哥

我有以下代码:

public Index () { 
    InitializeIndexAsync(); 
} 
 
async Task InitializeIndexAsync () { 
    State = IndexState.Initializing; 
    await Task.Factory.StartNew(async () => { 
        // Initialize other things. 
 
        await IndexAsync(); 
    }); 
 
    State = IndexState.Ready; 
} 

我希望“State = IndexState.Ready”在异步 lambda 完成之前不会被命中,但调试显示该行在线程启动之前很久就被命中了。这是为什么?

请您参考如下方法:

StartNew does not understand async lambdas ,所以当你传递一个 async 时lambda,它将返回一个 Task<Task> .从概念上讲,“外部”任务仅代表 async 的开始 lambda ; “内部”任务代表 async 的完成 lambda 。

这是 reasons that StartNew is the wrong choice for async code 之一,正如我在我的博客上解释的那样。更好的解决方案是使用 Task.Run , 这是用 async 设计的记在心里:

async Task InitializeIndexAsync () { 
  State = IndexState.Initializing; 
  await Task.Run(async () => { 
    // Initialize other things. 
 
    await IndexAsync(); 
  }); 
 
  State = IndexState.Ready; 
}