有没有一种方法可以在等待中更改Thread.CurrentPrincipal并在稍后使用它,而无需传递或返回它?还是这不安全,并且永远不应该使用异步?我知道有线程更改,但认为async/await会为我处理同步问题。
[TestMethod]
public async Task AsyncTest()
{
var principalType = Thread.CurrentPrincipal.GetType().Name;
// principalType = WindowsPrincipal
// Thread.CurrentThread.ManagedThreadId = 11
await Task.Run(() =>
{
// Tried putting await Task.Yield() here but didn't help
Thread.CurrentPrincipal = new UserPrincipal(Thread.CurrentPrincipal.Identity);
principalType = Thread.CurrentPrincipal.GetType().Name;
// principalType = UserPrincipal
// Thread.CurrentThread.ManagedThreadId = 10
});
principalType = Thread.CurrentPrincipal.GetType().Name;
// principalType = WindowsPrincipal (WHY??)
// Thread.CurrentThread.ManagedThreadId = 10
}
HttpContext.Current.User
,它可以给你你所需要的行为。 - Scott ChamberlainTask.Run
)。 - Scott Chamberlain