【发布时间】:2020-01-29 03:25:41
【问题描述】:
我有以下控制台应用程序:
namespace AsyncConsole
{
using System;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
internal static class Program
{
#region Private implementation
private static void Main()
{
Console.WriteLine(Thread.CurrentPrincipal.Identity.Name);
Program.RunAsync()
.GetAwaiter()
.GetResult();
}
private static async Task RunAsync()
{
for (;;)
{
using (var threadIdentity = WindowsIdentity.GetCurrent(true))
{
if (threadIdentity != null)
{
throw new InvalidOperationException($"Must not be impersonating {threadIdentity.Name} at the beginning of the request");
}
}
await Task.Yield();
using (var threadIdentity = WindowsIdentity.GetCurrent(true))
{
if (threadIdentity != null)
{
throw new InvalidOperationException($"{Thread.CurrentThread.ManagedThreadId} must not be impersonating {threadIdentity.Name} after first Yield");
}
}
using (var identity = WindowsIdentity.GetCurrent())
using (identity.Impersonate())
{
await Task.Yield();
}
using (var threadIdentity = WindowsIdentity.GetCurrent(true))
{
if (threadIdentity != null)
{
throw new InvalidOperationException($"{Thread.CurrentThread.ManagedThreadId} must not be impersonating {threadIdentity.Name} after disposing impersonation context");
}
}
}
}
#endregion
}
}
为什么会中线
throw new InvalidOperationException($"{Thread.CurrentThread.ManagedThreadId} must not be impersonating {threadIdentity.Name} after first Yield")
看起来WindowsIdentity 卡在某个后台线程中。
如果我注释掉该行,为什么问题会消失
Console.WriteLine(Thread.CurrentPrincipal.Identity.Name)
【问题讨论】:
-
模拟是每个线程的概念,但任务没有线程亲和性。在“等待”之后,可以在不同的线程上继续执行。
-
执行上下文确实流经异步点。
-
好的,我相信你的话,.NET 做了额外的工作来保护身份。但另一方面,它似乎不起作用?在原始 Win32 中,协程不传输线程标识。抱歉,我无法为您提供 .NET 特定部分的帮助。
-
当然有。 QueueUserWorkItem、I/O Completion Ports 等都保留线程安全上下文。
-
Win32 默认不会在线程之间传输安全上下文。你必须ask for it explicitly via WT_TRANSFER_IMPERSONATION。 I/O 完成端口没有任何用于传输模拟上下文的选项 - 如果需要,这完全是应用程序的责任。