public static void RunImpersonatedAsyncTest()
    {
        var testData = new RunImpersonatedAsyncTestInfo();

        BeginTask(testData);

        // Wait for the SafeHandle that was disposed in BeginTask() to actually be closed
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.WaitForPendingFinalizers();

        testData.continueTask.Release();
        testData.task.CheckedWait();
        if (testData.exception != null)
        {
            throw new AggregateException(testData.exception);
        }
    }
 private static void BeginTask(RunImpersonatedAsyncTestInfo testInfo)
 {
     testInfo.continueTask = new SemaphoreSlim(0, 1);
     using (SafeAccessTokenHandle token = WindowsIdentity.GetCurrent().AccessToken)
     {
         WindowsIdentity.RunImpersonated(token, () =>
         {
             testInfo.task = Task.Run(async() =>
             {
                 try
                 {
                     Task <bool> task = testInfo.continueTask.WaitAsync(ThreadTestHelpers.UnexpectedTimeoutMilliseconds);
                     Assert.True(await task.ConfigureAwait(false));
                 }
                 catch (Exception ex)
                 {
                     testInfo.exception = ex;
                 }
             });
         });
     }
 }