-
Notifications
You must be signed in to change notification settings - Fork 59
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
41 changed files
with
1,217 additions
and
594 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
using System; | ||
|
||
namespace YaR.MailRuCloud.Api.Base | ||
{ | ||
public class Cached<T> | ||
{ | ||
private readonly TimeSpan _duration; | ||
private DateTime _expiration; | ||
private Lazy<T> _value; | ||
private readonly Func<T> _valueFactory; | ||
|
||
public T Value | ||
{ | ||
get | ||
{ | ||
RefreshValueIfNeeded(); | ||
return _value.Value; | ||
} | ||
} | ||
|
||
public Cached(Func<T> valueFactory, TimeSpan duration) | ||
{ | ||
_duration = duration; | ||
_valueFactory = valueFactory; | ||
|
||
RefreshValueIfNeeded(); | ||
} | ||
|
||
private readonly object _refreshLock = new object(); | ||
|
||
private void RefreshValueIfNeeded() | ||
{ | ||
if (DateTime.Now >= _expiration) | ||
{ | ||
lock (_refreshLock) | ||
{ | ||
if (DateTime.Now >= _expiration) | ||
{ | ||
_value = new Lazy<T>(_valueFactory); | ||
_expiration = DateTime.Now.Add(_duration); | ||
} | ||
} | ||
} | ||
} | ||
|
||
public override string ToString() | ||
{ | ||
return Value.ToString(); | ||
} | ||
|
||
public void Expire() | ||
{ | ||
lock (_refreshLock) | ||
{ | ||
_expiration = DateTime.MinValue; | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.