Perform some functions parallel in the async interval?

I have Timer and Im calling some functions in the 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; } 

It's not bad. I can run functions in parallel, and one function cannot work 2 times, only once (so I want this). The problem is this: let's say function4() takes longer than my interval , so other functions must wait too. If I delete sync there, other functions will not wait, BUT another call to function4() may start on a different thread - and I do not want one of the functions to be executed twice. Any suggestions? thank you

+4
source share
1 answer

You will need to track each function individually so that you can control which functions you can initiate immediately and which ones you need to wait for, for example.

 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 blocks any functions that are already running, and allow you to run others that are not.

+3
source

Source: https://habr.com/ru/post/1434780/


All Articles