Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 清理静态引用_C#_.net_Multithreading_Garbage Collection - Fatal编程技术网

C# 清理静态引用

C# 清理静态引用,c#,.net,multithreading,garbage-collection,C#,.net,Multithreading,Garbage Collection,我有一个静态类,带有一些信息的静态字典。 字典将key作为WeakReference,我不想阻止对真正的key对象进行垃圾收集 代码示例: public static class ThreadHelper { private static readonly object syncRoot = new object(); private static Dictionary<WeakReference, ThreadInfo> threadInfos = new Dict

我有一个静态类,带有一些信息的静态字典。 字典将key作为WeakReference,我不想阻止对真正的key对象进行垃圾收集

代码示例:

public static class ThreadHelper {
    private static readonly object syncRoot = new object();
    private static Dictionary<WeakReference, ThreadInfo> threadInfos = new Dictionary<WeakReference, ThreadInfo>();

    // some static thread safe methods for adding, removing and changes items
}

我仍然不明白为什么使用WeakReference作为键是个坏主意,但现在这并不重要,我是否应该使用某种结构类包装WeakReference,并使用包装器作为键?

能否在几行中显示如何检索元素?编辑中的部分看起来不是线程安全的,在查找ret和使用ret之间可以删除ret.Target。方法添加到问题的编辑部分。事实上,ret.Target从未更改。它在创建WR时设置了一次。ret.Target中可以完成的唯一更改是ret.Target的垃圾收集及其正确行为。在本例中,object.ReferenceEquals tmpThread,thread返回false及其正确值。我编辑了这个问题,并向所有成员提供了完整的源代码。
private static WeakReference FindThreadReference( Thread thread ) {
    WeakReference ret = null;

    WeakReference[] keys;
    lock ( syncRoot ) {
        keys = threadInfos.Keys.ToArray();
    }

    foreach ( var key in keys ) {
        if ( key.IsAlive ) {
            var tmpThread = key.Target;
            if ( object.ReferenceEquals( tmpThread, thread ) ) {
                ret = key;
            }
        }
    }

    return ret;
}