The method below should return true for the first call and false for any other call.
Are there any problems with this? Is it safe to use the reset event to lock?
private ManualResetEvent _resetEvent = new ManualResetEvent(false); public bool AmIFirst() { lock (_resetEvent) { bool first = !_resetEvent.WaitOne(0); if (first) _resetEvent.Set(); return first; } }
Edit: I made some changes after viewing the comments. I am stuck on ManualResetEvent due to a previous design idea. I don’t need it at all.
class ActionSynchronizer { private Timer _expirationTimer; private object _locker = new object(); private bool _executionRequired = true; private SomeDelegate _onExpired = delegate { }; public ActionSynchronizer(SomeDelegate onExpired) { _onExpired = onExpired; expirationTimer = new Timer(OnExpired, null, 30000, Timeout.Infinite); } public bool IsExecutionRequired() { if (!_executionRequired) return false; lock (_locker) { if (_executionRequired) { _executionRequired = false; return true; } return false; } } private void OnExpired(object state) { if (_executionRequired) { lock (_locker) { if (_executionRequired) { _executionRequired = false;
source share