问题描述
假设我在 C# .Net Core 中有一个 async
方法:
public Task<ResultClass> Action() { ... }
调用有什么区别:ResultClass res = await Action();
并调用:ResultClass res = Action().ConfigureAwait(false).GetAwaiter().GetResult();
解决方法
await 关键字将在工作期间释放当前线程。因此,如果您的线程数量有限,这真的很有用。
“GetAwaiter().GetResult()”会同步执行相同的操作,因此当前线程将在工作期间被阻塞。
“ConfigureAwait(false)”是一种在同步代码中没有意义的配置,但对 await
很有用await Action().ConfigureAwait(false);
确保将直接调用以下内容并避免潜在的死锁。