在使用 ConfigureAwait(false) 的引用库中使用 Thread.CurrentPrincipal 的声明会造成任何问题,还是 ExecutionContext 的逻辑调用上下文的流动会在那里照顾我?(到目前为止,我的阅读和测试表明它会)。
示例 WebAPI 控制器操作:
[CustomAuthorizeThatSetsCurrentUsersClaimsToThreadCurrentContextAndHttpContextCurrentUser]
public async Task<Order> Get(int orderId)
{
return await _orderBusinessLogicLibrary.LoadAsync(orderId); // defaults to .ConfigureAwait(true)
}
来自外部引用库的示例加载函数:
[ClaimsPrincipalPermission(
SecurityAction.Demand,
Operation="Read",
Resource="Orders")]
[ClaimsPrincipalPermission(
SecurityAction.Demand,
Operation="Read",
Resource="OrderItems")]
public async Task<Order> Load(int orderId)
{
var order = await _repository.LoadOrderAsync(orderId).ConfigureAwait(false);
// here's the key line.. assuming this lower-level function is also imposing
// security constraints in the same way this method does, would
// Thread.CurrentPrincipal still be correct inside the function below?
order.Items = await _repository.LoadOrderItemsAsync(orderId).ConfigureAwait(false);
return order;
}
此外,答案不能是“那么不要使用 ConfigureAwait(false)!”。这可能会导致其他问题,例如死锁(不要阻塞异步代码)。