Skip to content

Commit

Permalink
Fix lock semantics ref counting in mrucache
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt Connew committed Dec 15, 2020
1 parent 829604e commit 4d25472
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.


using System.Collections.Generic;
using System.ServiceModel;
using System.Threading;

namespace System.Runtime
{
Expand All @@ -19,15 +17,26 @@ internal class MruCache<TKey, TValue> : IDisposable
private readonly int _highWatermark;
private CacheEntry _mruEntry;
private int _refCount = 1;
private object _mutex = new object();

public MruCache(int watermark)
: this(watermark * 4 / 5, watermark)
{
}

public void AddRef()
// Returns whether the cache can be used by the caller after calling AddRef
public bool AddRef()
{
Interlocked.Increment(ref _refCount);
lock(_mutex)
{
if (_refCount == 0)
{
return false;
}

_refCount++;
return true;
}
}

//
Expand Down Expand Up @@ -209,8 +218,12 @@ public bool TryGetValue(TKey key, out TValue value)

public void Dispose()
{
int refCount = Interlocked.Decrement(ref _refCount);
Fx.Assert(_refCount >= 0, "Ref count shouldn't go below zero");
int refCount;
lock (_mutex)
{
refCount = --_refCount;
}
Fx.Assert(refCount >= 0, "Ref count shouldn't go below zero");
if (refCount == 0)
{
Dispose(true);
Expand All @@ -221,10 +234,13 @@ protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!IsDisposed)
lock (_mutex)
{
IsDisposed = true;
Clear(true);
if (!IsDisposed)
{
IsDisposed = true;
Clear(true);
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -415,14 +415,10 @@ public override T GetProperty<T>(BindingContext context)

private MruCache<string, HttpClient> EnsureHttpClientCache()
{
if (_httpClientCache == null || _httpClientCache.IsDisposed)
if (_httpClientCache == null || !_httpClientCache.AddRef())
{
_httpClientCache = new MruCache<string, HttpClient>(10);
}
else
{
_httpClientCache.AddRef();
}

return _httpClientCache;
}
Expand Down

0 comments on commit 4d25472

Please sign in to comment.