我们有一些数据源类来处理一次性资源的操作,就像这样:
(译注:指实现了 IDisposable 接口的类)
public class SomeDataStore
{
private readonly object dictionaryLock = new object();
private readonly Dictionary<uint, SomeDisposableClass> dataStore = new Dictionary<uint, SomeDisposableClass>();
public bool Remove(uint key)
{
bool returnValue = false;
lock (dictionaryLock)
{
returnValue = dataStore.Remove(key);
}
//OR...
lock (dictionaryLock)
{
SomeDisposableClass element;
if (dataStore.TryGetValue(key, out element))
{
element.Dispose();
returnValue = dataStore.Remove(key);
}
}
return returnValue;
}
public void Clear()
{
lock (dictionaryLock)
{
dataStore.Clear();
}
//OR...
lock (dictionaryLock)
{
foreach (var value in dataStore.Values)
value.Dispose();
dataStore.Clear();
}
}
//Some other Datastore access members
}
public class SomeDisposableClass : IDisposable
{
public void Dispose()
{
//Dispose resources..
}
}
不确定哪个版本更好以及为什么?Dictionary
的 Clear
或者 Remove
内部是否处理 disposable
资源?
Dispose
方法的代码是创建该对象的代码。SomeDataStore
假定拥有该对象的所有权是有一定风险的。很难确定,因为你的代码中没有显示添加对象,更不用说是谁创建了它了。 - user585968ConcurrentDictionary
替代带有lock
的Dictionary
,这样可以更好地处理线程安全问题。不过这并不能解决你目前的问题。 - mjwillsDispose
,我希望该方法能更清晰地表达其意图,例如RemoveAndDispose
。或者,让Remove
返回SomeDisposableClass
,这样调用者就可以使用SomeDataStore.Remove(key)?.Dispose()
(如果他们愿意的话)。 - mjwills