John Ryann
John Ryann

Reputation: 2393

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);
    }
}

Upvotes: 2

Views: 6083

Answers (3)

Andre Calil
Andre Calil

Reputation: 7692

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

Upvotes: 4

Avada Kedavra
Avada Kedavra

Reputation: 8691

You could simply do:

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

public static void t1(object c)
{
  Class1 class1 = (Class1)c;
  ...
}

MSDN: ParameterizedThreadStart Delegate


Or even better:

Thread thread = new Thread(() => t1(new Class1()));

public static void t1(Class1 c)
{
  // no need to cast the object here.
  ...
}

This approach permits multiple arguments and does not require you to cast the object to the desired class/struct.

Upvotes: 4

jtimperley
jtimperley

Reputation: 2544

private static void DoSomething()
{
    Class1 whatYouWant = new Class1();
    Thread thread = new Thread(DoSomethingAsync);
    thread.Start(whatYouWant);
}

private static void DoSomethingAsync(object parameter)
{
    Class1 whatYouWant = parameter as Class1;
}

Upvotes: 2

Related Questions