I have a method (let’s call it “CheckAll”) that is called from multiple areas of my program, and can therefore be called for a 2nd time before the 1st time has completed.
To get around this I have implemented a “lock” that (if I understand it correctly), halts the 2nd thread until the 1st thread has completed.
However what I really want is for this 2nd call to return to the calling method immediately (rather than halt the thread), and to schedule CheckAll to be run again once it has completed the 1st time.
I could setup a timer to do this but that seems cumbersome and difficult. Is there a better way?
Easy/cheap implementation.
Just on a side note, this can have some race conditions. Better implementation would be to use ConcurrentQueue introduced in .NET 4 which handles all the threading craziness for you.
Update
Here’s a more ‘cool’ implementation using ConcurrentQueue (turns out we don’t need TPL):
Note
I use a real Thread instead of a TPL Task because a Task doesn’t hold on to a real thread as an optimization. When there’s no Thread, that means at the time your application closes, any waiting CheckAll requests are ignored. (I got bitten hard by this when I thought I’m so smart to call my logging methods in a task once, which ignored a couple of dozen log records when closing. CLR checks and waits for any waiting threads when gracefully exiting).