Reputation: 1327
I have a Timer and Im calling some functions in an interval. Right now I have something like this:
private System.Timers.Timer timer;
private int sync;
void Start()
{
timer = new System.Timers.Timer(interval);
timer.Elapsed += new ElapsedEventHandler(Elapsed);
timer.Enabled = true;
}
void Elapsed(object s, ElapsedEventArgs e)
{
if (System.Threading.Interlocked.CompareExchange(ref sync, 1, 0) == 0)
{
Parallel.Invoke( () => Function1(), () => Function2(), () => Function3(),
() => Function4() );
}
sync = 0;
}
This is not bad. I can start the functions parallel AND one function cannot run 2+ times, just once (this is how I want it). The problem is: lets say function4()
takes longer then my interval
, so the other functions have to wait too. If I remove the sync
there, the other functions wont wait BUT another function4()
call could start in another thread - and I dont want that one functions is running twice. Any suggestions? Thank you
Upvotes: 4
Views: 470
Reputation: 82096
You would have to keep track of each function individually so you have control on which functions you can initiate right away and which ones you need to wait on e.g.
private AutoResetEvent f1 = new AutoResetEvent(true);
private AutoResetEvent f2 = new AutoResetEvent(true);
...
void Elapsed(object s, ElapsedEventArgs e)
{
...
Parallel.Invoke(() => { f1.WaitOne(); Function1(); f1.Set(); },
() => { f2.WaitOne(); Function2(); f2.Set(); }
...
...
}
Something like this would block any functions that are already executing and allow other ones to start which aren't.
Upvotes: 3