多线程设计模式
我有一个可以被多个线程访问的类的实例。多线程设计模式
这个类内部是一个[ThreadStatic]
变量,它存储各种对象。
我现在需要我的班级的第二个实例,我希望它有一个单独的对象存储在里面。
目前,同一个线程中的两个实例将共享同一个对象存储。我不想要这个。
我能想到的唯一的解决办法是:
有一个静态IDictionary<int, TObjectStore>
其中int
是线程ID,并通过一些方法或吸气访问此:
static TObjectStore ObjectStore {
get {
// create the instance here if its the first-access from this thread, with locking etc. for safety
return objectStore[Thread.CurrentThread.Id];
}
}
这个虽然问题当特定线程结束时,如何处理TObjectStore
?我认为我正确地认为,在我目前的实施中,GC会简单地捡起它?
感谢
静态字段是不是真的在任何实例,所以我想你现在需要一个实例字段。在这种情况下,你想有一个ThreadLocal<T>
:
ThreadLocal<SomeType> store = new ThreadLocal<SomeType>(() => {
// initializer, used when a new thread accesses the value
return ...
});
这家店将可用于收集与实例一起,如将任何内容(只要他们没有其他地方引用,很明显)。
只是为了提供更多的信息,以马克的回答http://blogs.clariusconsulting.net/kzu/a-better-way-to-implement-the-singleton-anti-pattern-for-easier-testing-using-ambientsingleton/
这篇文章讨论了各种方法,您的问题,与代码示例。
有趣!有+1 – 2012-01-13 12:30:56
TIL关于'ThreadLocal ' – 2012-01-12 13:54:18