我正在使用CLR内存诊断库来获取正在运行的进程中所有线程的堆栈跟踪:

        var result = new Dictionary<int, string[]>();

        var pid = Process.GetCurrentProcess().Id;

        using (var dataTarget = DataTarget.AttachToProcess(pid, 5000, AttachFlag.Passive))
        {
            string dacLocation = dataTarget.ClrVersions[0].TryGetDacLocation();
            var runtime = dataTarget.CreateRuntime(dacLocation); //throws exception

            foreach (var t in runtime.Threads)
            {
                result.Add(
                    t.ManagedThreadId,
                    t.StackTrace.Select(f =>
                    {
                        if (f.Method != null)
                        {
                            return f.Method.Type.Name + "." + f.Method.Name;
                        }

                        return null;
                    }).ToArray()
                );
            }
        }

我从here那里获得了这段代码,它似乎对其他人有用,但是它在指示的行上向我抛出了异常,并显示了This runtime is not initialized and contains no data.消息
dacLocation设置为C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\mscordacwks.dll

最佳答案

ClrMD当前不支持.NET 4.6。有一个开放的拉取请求on GitHub只需一行就可以解决此问题。当然,您可以克隆项目并构建自己的ClrMD,而不会出现此问题。

或者,我可以分享过去几周来一直在使用的临时hack:

public static ClrRuntime CreateRuntimeHack(this DataTarget target, string dacLocation, int major, int minor)
{
    string dacFileNoExt = Path.GetFileNameWithoutExtension(dacLocation);
    if (dacFileNoExt.Contains("mscordacwks") && major == 4 && minor >= 5)
    {
        Type dacLibraryType = typeof(DataTarget).Assembly.GetType("Microsoft.Diagnostics.Runtime.DacLibrary");
        object dacLibrary = Activator.CreateInstance(dacLibraryType, target, dacLocation);
        Type v45RuntimeType = typeof(DataTarget).Assembly.GetType("Microsoft.Diagnostics.Runtime.Desktop.V45Runtime");
        object runtime = Activator.CreateInstance(v45RuntimeType, target, dacLibrary);
        return (ClrRuntime)runtime;
    }
    else
    {
        return target.CreateRuntime(dacLocation);
    }
}

我知道,这太可怕了,需要依靠反射(reflection)。但是至少它现在可以使用,并且您不必更改代码。

关于c# - 创建运行时,ClrMd引发异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31633541/

10-16 18:59