为什么在UnobservedTaskException中生成一个小型转储会引发AccessViolationException

时间:2014-06-17 04:23:07

标签: c# multithreading c#-4.0 exception-handling task-parallel-library

我有一个流程,当发生未处理的异常时(使用AppDomain.CurrentDomain.UnhandledExceptionTaskScheduler.UnobservedTaskException)生成小型转储。转储在未处理的异常处理程序中工作正常,但在从未观察到的任务异常处理程序调用时生成AccessViolationException(请参阅下面的示例代码)。

从我在MSDN和StackOverflow上看到的,两个代码路径之间的关键区别在于后者发生在终结器线程中,我猜测线程状态或安全性正在阻止此操作成功。

是否有任何人有任何信息或链接可以解释为什么迷你转储操作在未观察到的线程异常情况下失败?我很高兴接受我正在努力的事情是不可能的,但我真的想确认这一点并知道为什么......

下面的代码通过触发任务中的未处理异常并强制垃圾收集触发未观察到的线程异常来演示我的问题。然后,MiniDumpWriteDump调用会生成AccessViolationException

using System;
using System.IO;
using System.Runtime.ConstrainedExecution;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;

namespace ExceptionTest
{
    public class ClassThatThrows
    {
        public void Throw()
        {
            var t = new Task(() =>
            {
                Console.WriteLine("Throwing...");
                throw new NullReferenceException();
            });

            t.Start();
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            TaskScheduler.UnobservedTaskException += HandleUnobservedTaskException;

            var test = new ClassThatThrows();
            test.Throw();

            Thread.Sleep(1000);

            GC.Collect();
            GC.WaitForPendingFinalizers();

            Console.ReadLine();
        }

        [HandleProcessCorruptedStateExceptions]
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        [SecurityCritical]
        private static void HandleUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            WriteMiniDump();
        }

        private static void WriteMiniDump()
        {
            var miniDumpFilePath = GetMiniDumpFilePath();

            using (var fileStream = new FileStream(miniDumpFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                MiniDumpExceptionInformation exceptionInfo;
                exceptionInfo.ThreadId = GetCurrentWin32ThreadId();
                exceptionInfo.ClientPointers = false;
                exceptionInfo.ExceptionPointers = Marshal.GetExceptionPointers();

                var currentProcess = GetCurrentProcess();
                var currentProcessId = GetCurrentProcessId();

                var safeFileHandle = fileStream.SafeFileHandle;
                MiniDumpWriteDump(currentProcess, currentProcessId, safeFileHandle.DangerousGetHandle(), 0x00000000, ref exceptionInfo, IntPtr.Zero, IntPtr.Zero);
            }
        }

        protected static string GetMiniDumpFilePath()
        {
            var timestamp = DateTime.Now.ToString("yyyyMMddTHHmmss");
            var fileName = string.Format("MiniDump.{0}.mdmp", timestamp);
            return Path.Combine(Path.GetTempPath(), fileName);
        }

        [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
        public static extern uint GetCurrentWin32ThreadId();

        [DllImport("dbghelp.dll", EntryPoint = "MiniDumpWriteDump", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
        public static extern bool MiniDumpWriteDump(IntPtr hProcess, uint processId, IntPtr hFile, uint dumpType, ref MiniDumpExceptionInformation expParam, IntPtr userStreamParam, IntPtr callbackParam);

        [DllImport("kernel32.dll", EntryPoint = "GetCurrentProcess", ExactSpelling = true)]
        public static extern IntPtr GetCurrentProcess();

        [DllImport("kernel32.dll", EntryPoint = "GetCurrentProcessId", ExactSpelling = true)]
        public static extern uint GetCurrentProcessId();

        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct MiniDumpExceptionInformation
        {
            public uint ThreadId;
            public IntPtr ExceptionPointers;
            [MarshalAs(UnmanagedType.Bool)]
            public bool ClientPointers;
        }
    }
}

由于

1 个答案:

答案 0 :(得分:0)

我尝试从家用机器上实现Yuval的建议而无法重现问题,这立即让我考虑了原始机器上的dbghelp.dll版本。

在我的可执行文件夹中放入最新的Windows 8.1 SDK中的dbghelp.dll之后,问题就消失了,所以我可以指责一个过时的dbghelp.dll,而不是创建小型转储的一些模糊的C#问题来自终结者线程。

作为参考,dbghelp.dll 6.1.7601.17514演示了此问题,并确认dbghelp.dll 6.3.9600.17029可以解决此问题。来自异常的调用堆栈(虽然没有透露太多)如下所示:

    ntdll.dll!NtWaitForSingleObject()
KernelBase.dll!WaitForSingleObjectEx()
msvcr110_clr0400.dll!__C_specific_handler()
ntdll.dll!RtlpExecuteHandlerForException()
ntdll.dll!RtlDispatchException()
ntdll.dll!KiUserExceptionDispatch()
dbghelp.dll!MiniDumpWriteDump()
[Managed to Native Transition]  
    ExceptionTest.exe!ExceptionTest.Program.WriteMiniDump() Line 66 C#
ExceptionTest.exe!ExceptionTest.Program.HandleUnobservedTaskException(object sender, System.Threading.Tasks.UnobservedTaskExceptionEventArgs e) Line 48 C#
mscorlib.dll!System.Threading.Tasks.TaskScheduler.PublishUnobservedTaskException(object sender, System.Threading.Tasks.UnobservedTaskExceptionEventArgs ueea)
mscorlib.dll!System.Threading.Tasks.TaskExceptionHolder.Finalize()