【问题标题】:List all custom data stored in AppDomain列出存储在 AppDomain 中的所有自定义数据
【发布时间】:2012-12-07 12:59:51
【问题描述】:

为了存储发生错误时的进程状态,我想列出存储在 AppDomain 中的所有(自定义)数据(通过 SetData)。 LocalStore 属性是私有的,并且 AppDomain 类不可继承。 有没有办法枚举这些数据?

【问题讨论】:

  • 为什么不将所有键信息(之前使用 SetData 设置)存储在某个集合中,并在对该集合中的每个键查询 GetData 之后?
  • 我正在寻找一种解决方案,其中流程不需要使用特定的实现。由于我认为不可能,因此存储密钥的 AppDomain 的扩展方法已通过。谢谢你的回复。如果您还有其他线索,请不要犹豫。

标签: c# appdomain


【解决方案1】:
        AppDomain domain = AppDomain.CurrentDomain;
        domain.SetData("testKey", "testValue");

        FieldInfo[] fieldInfoArr = domain.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
        foreach (FieldInfo fieldInfo in fieldInfoArr)
        {

            if (string.Compare(fieldInfo.Name, "_LocalStore", true) != 0)
                continue;
            Object value = fieldInfo.GetValue(domain);
            if (!(value is Dictionary<string,object[]>))
                return;
            Dictionary<string, object[]> localStore = (Dictionary<string, object[]>)value;
            foreach (var item in localStore)
            {
                Object[] values = (Object[])item.Value;
                foreach (var val in values)
                {
                    if (val == null)
                        continue;
                    Console.WriteLine(item.Key + " " + val.ToString());
                }
            }


        }

【讨论】:

  • 不错的解决方案。感谢您的回复。
【解决方案2】:

基于Frank59's的回答,但更简洁一点:

var appDomain = AppDomain.CurrentDomain;
var flags = BindingFlags.NonPublic | BindingFlags.Instance;
var fieldInfo = appDomain.GetType().GetField("_LocalStore", flags);
if (fieldInfo == null)
    return;
var localStore = fieldInfo.GetValue(appDomain) as Dictionary<string, object[]>;
if (localStore == null)
    return;
foreach (var key in localStore.Keys)
{
    var nonNullValues = localStore[key].Where(v => v != null);
    Console.WriteLine(key + ": " + string.Join(", ", nonNullValues));
}

【讨论】:

    【解决方案3】:

    相同的解决方案,但作为 F# 扩展方法。可能不需要空检查。 https://gist.github.com/ctaggart/30555d3faf94b4d0ff98

    type AppDomain with
        member x.LocalStore
            with get() =
                let f = x.GetType().GetField("_LocalStore", BindingFlags.NonPublic ||| BindingFlags.Instance)
                if f = null then Dictionary<string, obj[]>()
                else f.GetValue x :?> Dictionary<string, obj[]>
    
    let printAppDomainObjectCache() =
        for KeyValue(k,v) in AppDomain.CurrentDomain.LocalStore do
            printfn "%s" k
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多