Frage

I'd like to create a new thread for a member function. I currently use this code,

Thread thread = new Thread(new ThreadStart(c.DoSomethingElse));
thread.Start();

and it's working. But now I'd like to parameterize the member function.

I have this class:

class C1 {
  public void DoSomething() {}
  public void DoSomethingElse() {}

  public delegate void myDelegate(C1 c);
}

Then I have this function in some other class:

public void myFunction(C1.myDelegate func) {
  C1 c = new C1();

  func(c);  // this is working

  // but I want that the called function runs in it's own thread
  // so I tried...
  Thread thread = new Thread(new ThreadStart( func(c) ); // but the compile wants a
  thread.Start();                                        // method name and not a delegate
}

I call the myFunction as follows...

myFunction( (c) => c.DoSomething() );

So is it possible to do this. I mean, I can pass the delegate und call it with the object func(c). And I can create a new thread passing an object.memberfunction. But I don't know how to combine both, using the memberfunction delegate and passing it to the ThreadStart function. Any hints?

War es hilfreich?

Lösung

I would suggest using the Parallelism built into .NET.

Task.Factory.StartNew(() => func(c));

Andere Tipps

You need to use another overload of Thread.Start(parameter)

new Thread(c.DoSomethingElseWithParameter).Start(someparameter);

Edit:

For your own delegate try this.

   Thread thread = new Thread(() =>  func(c));
   thread.Start();

Note: your method signature should be of void MethodName(object obj) if not use a Lambda or Anonymous method

You can just do:

Thread thread = new Thread(new ThreadStart(() => func(c));

If you have access to 4.0, I recommend using the Task Parallel Library. Here's an example based on your code.

class TPL
{
    public delegate void myDelegate(object cgf);

    public static void Test(myDelegate func)
    {
        object c = new object();
        Task t = new Task(() => func(c));
        t.Start();
    }
}

Here's a link http://msdn.microsoft.com/en-us/library/dd537609.aspx

The TPL is worth looking at, especially the StartNew Method. It uses a Threadpool instead of explicit threads, so it might even be better performing.

You can pass a lambda exression as parameter. I've done that, worked smoothly.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top