Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a method to finish on another thread?

I am new to multi-thread programming in C#. My problem is that I don't know how to wait for a method that is being run on another thread to finish, before it can continue to 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 prints 0 on the console, which is not what I want (i.e. i = 100). What is the best way to do this? BTW, I don't have access to the runThread that is created in class A

Thanks.

EDIT:

It was a bit difficult to solve this problem without modifying a lot codes. Therefore, we ended up with adding a condition in the public void Start() with which it can decide whether to run the RunLoop in a separate thread or not. The condition was defined using an 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 };

Thanks everyone for help.

like image 451
Sina Torabi Avatar asked Mar 30 '16 12:03

Sina Torabi


1 Answers

The preferred method is to use the Task Parallel Library (TPL) and use Task with await.

If you must use Threads, then use a ManualResetEvent or ManualResetEventSlim to signal the end of a method.

void Main()
{
    var a = new A();
    a.Start();
    a.FinishedEvent.WaitOne();
    Console.WriteLine(a.Index);
}

// Define other methods and classes here
public class A
{
    ManualResetEvent mre = new ManualResetEvent(false);
    int i;

    public EventWaitHandle FinishedEvent
    {
        get { return mre; }
    }

    public int Index
    {
        get { return i; }
    }

    public A()
    {
        i = 0;
    }

    protected void RunLoop()
    {
        while (i < 1000)
        {
            i++;
        }
        mre.Set();
    }

    public void Start()
    {
        var runThread = new Thread(new ThreadStart(RunLoop));
        runThread.Start();
    }
}
like image 100
Ryan Avatar answered Sep 19 '22 17:09

Ryan