Reputation: 75
I would like find out a good solution for the following problem. For example I have 5 timer what I start from 1 thread. These timers finish their work after few second (this is a retry mechanism). And I would like to wait to all of the timers finish their work.
So the question is that, Is there any good pattern which can handle this problem? Or do you now a good solution which is not a bool collection and if all of the elements are true then all of the timer finished :D
Thank you for your answer in advance!
Upvotes: 0
Views: 1091
Reputation: 89
There are multiple solutions to your problem.
I would suggest you take a look at Rx (Reactive Extensions) if you are familiar with linq since they use a very similar syntax. Rx allows you to do a lot of things with all sorts of events.
Another way is to use TPL (task parallel library) as follows:
var timer1 = Task.Delay(1000);
var timer2 = Task.Delay(2000);
var timer3 = Task.Delay(3000);
await Task.WhenAll(timer1, timer2, timer3);
Notice that you have to call this from an async context. If you are not familiar with async/await I recommend you take a look at it. If you don't want to / can't take a look at it you could simply do the following:
Task.WhenAll(timer1, timer2, timer3).GetAwaiter().GetResult();
Upvotes: 0
Reputation: 63732
This sounds like you really want to use Task
instead of Timer
.
Silly example:
async Task DoAsync()
{
var allTheWork = new [] { Work(), Work(), Work() };
await Task.WhenAll(allTheWork);
// Did all the sub-tasks return true?
if (allTheWork.All(i => i.Result))
{
}
}
async Task<bool> Work()
{
var retries = 3;
while (retries-- > 0)
{
if (success) return true;
await Task.Delay(2000); // This is the timer; you can find better retry patterns of course
}
return false;
}
Upvotes: 4