forked from haoduotnt/aspnetwebstack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileExistenceCache.cs
79 lines (68 loc) · 2.75 KB
/
FileExistenceCache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Web.Hosting;
namespace System.Web.WebPages
{
/// <summary>
/// This class caches the result of VirtualPathProvider.FileExists for a short
/// period of time, and recomputes it if necessary.
///
/// The default VPP MapPathBasedVirtualPathProvider caches the result of
/// the FileExists call with the appropriate dependencies, so it is less
/// expensive on subsequent calls, but it still needs to do MapPath which can
/// take quite some time.
/// </summary>
internal class FileExistenceCache
{
private const int TicksPerMillisecond = 10000;
private readonly VirtualPathProvider _virtualPathProvider;
private readonly Func<string, bool> _virtualPathFileExists;
private ConcurrentDictionary<string, bool> _cache;
private long _creationTick;
private int _ticksBeforeReset;
public FileExistenceCache(VirtualPathProvider virtualPathProvider, int milliSecondsBeforeReset = 1000)
{
Contract.Assert(virtualPathProvider != null);
_virtualPathProvider = virtualPathProvider;
_virtualPathFileExists = virtualPathProvider.FileExists;
_ticksBeforeReset = milliSecondsBeforeReset * TicksPerMillisecond;
Reset();
}
// Use the VPP returned by the HostingEnvironment unless a custom vpp is passed in (mainly for testing purposes)
public VirtualPathProvider VirtualPathProvider
{
get { return _virtualPathProvider; }
}
public int MilliSecondsBeforeReset
{
get { return _ticksBeforeReset / TicksPerMillisecond; }
internal set { _ticksBeforeReset = value * TicksPerMillisecond; }
}
internal IDictionary<string, bool> CacheInternal
{
get { return _cache; }
}
public bool TimeExceeded
{
get { return (DateTime.UtcNow.Ticks - Interlocked.Read(ref _creationTick)) > _ticksBeforeReset; }
}
public void Reset()
{
_cache = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
DateTime now = DateTime.UtcNow;
long tick = now.Ticks;
Interlocked.Exchange(ref _creationTick, tick);
}
public bool FileExists(string virtualPath)
{
if (TimeExceeded)
{
Reset();
}
return _cache.GetOrAdd(virtualPath, _virtualPathFileExists);
}
}
}