public void func() { for(i=0;i<10;i++) { } for (j=0;j<10;j++) { } }
public void func() { // This code is on thread 1 Thread ta = new Thread(new ThreadStart(LoopA)); // create thread 2 for LoopA Thread tb = new Thread(new ThreadStart(LoopB)); // create thread 3 for LoopB ta.Start(); // Run LoopA on thread 2 tb.Start(); // Run LoopB on thread 3 // Join makes this thread wait until the thread being joined to has finished ta.Join(); // wait for thread 2 to finish tb.Join(); // now wait for thread 3 to finish // From this point on we know that both loops have completed } public void LoopA() { for (int i = 0; i < 1000; i++) { Console.WriteLine("i = " + i.ToString()); } } public void LoopB() { for (int j = 0; j < 1000; j++) { Console.WriteLine("j = " + j.ToString()); } }
What about employing the Task-Based Asynchronous Pattern?
private static async Task MainAsync() { await MyMethodAsync(); } private static async Task MyMethodAsync() { //start the tasks const int count = 10; Task<string> loopATask = Task.Run(() => LoopA(count)); Task<string> loopBTask = Task.Run(() => LoopB(count)); //await them to complete string resultA = await loopATask; string resultB = await loopBTask; Console.WriteLine(resultA + resultB); } public static string LoopA(int count) { for (int i = 0; i < count; i++) { Console.WriteLine("LoopA " + i); } return "LoopA has finished "; } public static string LoopB(int count) { for (int i = 0; i < count; i++) { Console.WriteLine("LoopB " + i); } return "LoopB has finished "; }
public void func() { for(i=0;i<10;i++) { aaa(); bbb(); ccc(); } for (i=0;i<10;i++) { yyy(); zzz(); } }
public void func() { for(i=0;i<10;i++) { aaa(); bbb(); ccc(); yyy(); zzz(); } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)