WindowsIdentity. Имитировать в некоторых асинхронных сценариях утечки личности - PullRequest
0 голосов
/ 29 сентября 2019

У меня есть следующее консольное приложение:

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...