Reputation: 47
Hi I want run 3 methods at the same time and the others wait until any methods is finish. How can i do this? Here's what I've done so far.
public static List<Action> actions;
public static int ms = 1;
public static void s1()
{
actions = new List<Action>();
actions.Add(drivers1);
actions.Add(drivers2);
actions.Add(drivers3);
actions.Add(drivers4);
var maxThreads = 3;
int j = 1;
while (true)
{
if (j == 1){
if (ms <= 3) {
while (true) {
if (actions.Count() < 1)
{
j = 0;
}
else
{
thread = new Thread(new ThreadStart(actions[0]));
thread.Start();
}
}
}
else
{
while (true)
{
if (ms <= 3)
{
break;
}
else
{
Thread.Sleep(1000);
}
}
}
}
else
{
break;
}
}
}
here image example: https://drive.google.com/open?id=1_qK2Yu2RjebAfKFdYFovShGR5GiuwzBI
Upvotes: 1
Views: 128
Reputation: 649
Consider Wrapping your methods in a Task then you can easily use Task.WaitAny Method
var task1 = Task.Run(() => Method1() );
var task2 = Task.Run(() => Method2() );
var task3 = Task.Run(() => Method3() );
Task.WaitAny(task1, task2, task3);
note that tasks wrap exceptions so in case u done this and any exception happened in Methods 1,2,3 the catch block will never be executed :
try
{
Task task1 = Task.Run(() => Method1());
Task task2 = Task.Run(() => Method2());
Task task3 = Task.Run(() => Method3());
Task.WaitAny(task1, task2, task3);
}
catch (System.Exception)
{
throw;
}
but you case still get the status of the Task variable itself
Upvotes: 3