-
-
Save afifmohammed/8107394 to your computer and use it in GitHub Desktop.
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
public class ConcurrentGateway | |
{ | |
private ConcurrentQueue<Action> _workQueue = new ConcurrentQueue<Action>(); | |
private int _writeLock = 0; | |
private static AutoResetEvent _waitEvent = new AutoResetEvent(false); | |
protected static AutoResetEvent GetThreadWaitEvent() | |
{ | |
//returns same event for all threads ,but we could easily provide a | |
//separate event for each thread to reduce lock contention | |
return _waitEvent; | |
} | |
public void DoSynchronized(Action act) | |
{ | |
bool done = false; | |
var ev = GetThreadWaitEvent(); | |
_workQueue.Enqueue(delegate() //enqueue the work TBD | |
{ | |
act(); | |
done = true; | |
ev.Set(); | |
}); | |
int lk = Interlocked.CompareExchange(ref _writeLock, 1, 0); | |
if (lk == 1) | |
{ //I'm a writer thread, do all the work now | |
Action a2; | |
while(_workQueue.TryDequeue(out a2)) { | |
a2(); | |
} | |
var ov = Interlocked.CompareExchange(ref _writeLock, 0, 1); | |
System.Diagnostics.Debug.Assert(ov == 0); //release | |
} | |
else | |
{ //i'm not a writer so I have to wait | |
while (!done) | |
{ | |
ev.WaitOne(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment