1

So, I'm trying to pass an argument to a method that I want to participate in multithreading. So, I wrote code that looks like this:

    new Thread (Go(ineedthis)).Start();
    Go();

  static void Go(string ineedthis)
  {
    lock (locker)
    {
      if (!done) { Console.WriteLine ("Done"); done = true; }
    }
  }

However, I can't pass the argument ineedthis, because it will give an error when you insert it like I did in the first line. Conversely, if you don't give an argument when making the thread for the method, it will also give an error.

So, how does one pass an argument to a method when creating a thread?

Thanks! Note: I just started c# yesterday, so I'm totally new to this. Please explain well so I get more out of it!

EDIT - Errors:

Error   1   The best overloaded method match for 'System.Threading.Thread.Thread(System.Threading.ParameterizedThreadStart)' has some invalid arguments     23  21  test


Error   2   Argument 1: cannot convert from 'method group' to 'System.Threading.ParameterizedThreadStart'   23  32  test
Jakexx360
  • 25
  • 3

5 Answers5

3

I think you are looking for something more like this:

  var t = new Thread (Go); 
t.Start(ineedthis);

You first create a thread that details what the method will be when run on the background thread. You then start the thread, passing in any parameters as needed. See MSDN for more info.

Josh
  • 10,352
  • 12
  • 58
  • 109
1

You need a ParameterizedThreadStart delegate:

new Thread (Go).Start(ineedthis);

and the method signature needs to be object ineedthis, not string ineedthis:

static void Go(object ineedthis)
{
  string data = (string)ineedthis;
  lock (locker)
  {
    if (!done) { Console.WriteLine ("Done"); done = true; }
  }
}
Marcel N.
  • 13,726
  • 5
  • 47
  • 72
1

You can use Task Parallel Library for this.

Task.Factory.StartNew(() => Go("test"));
L.B
  • 114,136
  • 19
  • 178
  • 224
0

This should also work:

new Thread (() => Go(ineedthis)).Start();

That wraps the method call inside a zero-argument lambda that is assignable to a ThreadStart.

Rytmis
  • 31,467
  • 8
  • 60
  • 69
0
    Thread workerThread = new Thread (() => go("example"));
    workerThread.Start();
john Peralta
  • 771
  • 5
  • 3