Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi threading; pass object to another object

I need to pass an object to another object. I know I have to pass c to t1. How do I do this

Thread t = new Thread(t1);
t.Start();

private static void t1(Class1 c)
{
    while (c.process_done == false)
    {
        Console.Write(".");
        Thread.Sleep(1000);
    }
}
like image 910
John Ryann Avatar asked Feb 02 '26 12:02

John Ryann


1 Answers

Ok guys, everybody is missing the point the object is being used outside the thread as well. This way, it must be synchronized to avoid cross-thread exceptions.

So, the solution would be something like this:

//This is your MAIN thread
Thread t = new Thread(new ParameterizedThreadStart(t1));
t.Start(new Class1());
//...
lock(c)
{
  c.magic_is_done = true;
}
//...

public static void t1(Class1 c)
{
  //this is your SECOND thread
  bool stop = false;
  do
  {
    Console.Write(".");
    Thread.Sleep(1000);

    lock(c)
    {
      stop = c.magic_is_done;
    }
    while(!stop)
  }
}

Hope this helps.

Regards

like image 183
Andre Calil Avatar answered Feb 05 '26 00:02

Andre Calil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!