我已經閱讀了很多關於緩存和線程同步的SO和其他站點,但我仍然無法得到我的問題的答案。緩存,僅在更新資源時同步線程
.NET Thread Safety for Static Dictionary Cache
Why are locks performed on separate objects?
http://msdn.microsoft.com/en-us/magazine/cc188793.aspx
...
我試圖實現暴露它們只能從外部讀取資源的高速緩存。 這些資源可以更新,但不會經常發生,也不會花費太多時間。
基本上資源是關鍵值列表(id和字符串),並不真正大(百元素不多)。
所以,我不想鎖定讀取方法以避免同步開銷,因爲它在大多數情況下不是必需的,但是我希望在資源需要更新時使用它。
我的問題是:有沒有辦法做這樣的事情:
public class AFTypeCache<T> where T : class
{
private Dictionary<int, T> _types;
private Func<Dictionary<int, T>> _dataProvider;
private readonly object _sync = new object();
public void UpdateData()
{
// here something (?) to make sure no more threads are reading the resource
lock (_sync)
{
_types = _dataProvider();
}
}
public IEnumerable<int, T> Get()
{
// thought about something like that but I'm pretty sure this won't work...
if (_updating)
{
lock
{
return _types;
}
}
else
{
// I know not the way to get enumerator but that's not the point
return _types;
}
}
}
而且,是不是真的有用,試圖做到這一點還是我走錯了路,只是應在使用鎖Get
方法?
編輯:
好了一些谷歌搜索後,我將有一個更準確的問題:是否有可能知道,如果一個類引用是被其它線程使用,如果是這樣,等待此線程完成使用它?
我知道框架中有一個併發的詞典,但我認爲它鎖定了讀取的數據,這就是我想要避免的。我只需要將其鎖定在更新上(這不會經常發生)。 – ppetrov 2013-03-29 10:46:22