Skip to content
This repository was archived by the owner on Nov 20, 2018. It is now read-only.

Commit a49ba74

Browse files
benaadamsTratcher
authored andcommitted
Reduce Revision check calls via interface
1 parent e854d3a commit a49ba74

File tree

1 file changed

+25
-20
lines changed

1 file changed

+25
-20
lines changed

src/Microsoft.AspNetCore.Http.Features/FeatureReferences.cs

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -26,34 +26,39 @@ public FeatureReferences(IFeatureCollection collection)
2626
public TFeature Fetch<TFeature, TState>(
2727
ref TFeature cached,
2828
TState state,
29-
Func<TState, TFeature> factory)
29+
Func<TState, TFeature> factory) where TFeature : class
3030
{
31-
var cleared = false;
32-
if (Revision != Collection.Revision)
31+
var revision = Collection.Revision;
32+
if (Revision == revision)
3333
{
34-
cleared = true;
35-
Cache = default(TCache);
36-
Revision = Collection.Revision;
34+
// collection unchanged, use cached
35+
return cached ?? UpdateCached(ref cached, state, factory);
3736
}
3837

39-
var feature = cached;
40-
if (feature == null || cleared)
41-
{
42-
feature = Collection.Get<TFeature>();
43-
if (feature == null)
44-
{
45-
feature = factory(state);
38+
// collection changed, clear cache
39+
Cache = default(TCache);
40+
// empty cache is current revision
41+
Revision = revision;
4642

47-
Collection.Set(feature);
43+
return UpdateCached(ref cached, state, factory);
44+
}
4845

49-
Revision = Collection.Revision;
50-
}
51-
cached = feature;
46+
private TFeature UpdateCached<TFeature, TState>(ref TFeature cached, TState state, Func<TState, TFeature> factory) where TFeature : class
47+
{
48+
cached = Collection.Get<TFeature>();
49+
if (cached == null)
50+
{
51+
// create if item not in collection
52+
cached = factory(state);
53+
Collection.Set(cached);
54+
// Revision changed by .Set, update revision
55+
Revision = Collection.Revision;
5256
}
53-
return feature;
57+
58+
return cached;
5459
}
5560

56-
public TFeature Fetch<TFeature>(ref TFeature cached, Func<IFeatureCollection, TFeature> factory) =>
57-
Fetch(ref cached, Collection, factory);
61+
public TFeature Fetch<TFeature>(ref TFeature cached, Func<IFeatureCollection, TFeature> factory)
62+
where TFeature : class => Fetch(ref cached, Collection, factory);
5863
}
5964
}

0 commit comments

Comments
 (0)