I am new to multithreaded C # programming. My problem is that I donโt know how to wait for a method that runs on another thread to complete before it can continue the next line. For example, something like this
public class A { int i; public A() { i = 0; } protected void RunLoop() { while(i < 100) { i++; } } public void Start() { TimerResolution.TimeBeginPeriod(1); runThread = new Thread(new ThreadStart(RunLoop)); running = true; runThread.Start(); } } public class B { A classAInstance = new A(); A.Start(); Console.Writeline(i); }
Right now, it is printing 0 on the console, which is not what I want (that is, I = 100). What is the best way to do this? BTW, I do not have access to runThread , which is created in class A
Thanks.
EDIT:
It was a little difficult to solve this problem without changing the code codes. So we ended up adding a condition to public void Start() , with which it can decide whether to run RunLoop in a separate thread or not. The condition was defined using the Enum field.
public void Start() { TimerResolution.TimeBeginPeriod(1); running = true; if (runningMode == RunningMode.Asynchronous) { runThread = new Thread(new ThreadStart(RunLoop)); runThread.Start(); } else { RunLoop(); } }
and
public enum RunningMode { Asynchronous, Synchronous };
Thank you all for your help.
source share