Created
January 31, 2022 10:57
-
-
Save ogxd/81416412197c6b635d8cca3c0a451ead to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public class ManualOptionMonitor<T> : IOptionsMonitor<T> | |
{ | |
private readonly Dictionary<int, Action<T, string>> _listeners = new Dictionary<int, Action<T, string>>(); | |
private volatile int _nextId; | |
private T _currentValue; | |
public T CurrentValue | |
{ | |
get | |
{ | |
return _currentValue; | |
} | |
set | |
{ | |
if (!value.Equals(_currentValue)) | |
{ | |
_currentValue = value; | |
lock (_listeners) | |
{ | |
foreach (var listener in _listeners.Values) | |
{ | |
try | |
{ | |
listener(_currentValue, null); | |
} catch { } | |
} | |
} | |
} | |
} | |
} | |
public T Get(string name) => CurrentValue; | |
private event Action<T, string> _onChanged; | |
public IDisposable OnChange(Action<T, string> listener) | |
{ | |
lock (_listeners) | |
{ | |
_nextId++; | |
_listeners.Add(_nextId, listener); | |
return new OptionMonitorRegistration(this, _nextId); | |
} | |
} | |
private void Unregister(int id) | |
{ | |
lock (_listeners) | |
{ | |
_listeners.Remove(id); | |
} | |
} | |
public struct OptionMonitorRegistration : IDisposable | |
{ | |
private ManualOptionMonitor<T> _optionMonitor; | |
private int _id; | |
public OptionMonitorRegistration(ManualOptionMonitor<T> optionMonitor, int id) | |
{ | |
_optionMonitor = optionMonitor; | |
_id = id; | |
} | |
public void Dispose() | |
{ | |
_optionMonitor.Unregister(_id); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment