9

Consider the code:

class Work
{
    public void DoStuff(string s)
    {
        Console.WriteLine(s);
        // .. whatever
    }
}
class Master
{
    private readonly Work work = new Work();

    public void Execute()
    {
        string hello = "hello";

        // (1) is this an ugly hack ?
        var thread1 = new Thread(new ParameterizedThreadStart(o => this.work.DoStuff((string)o)));           
        thread1.Start(hello);
        thread1.Join();

        // (2) is this similar to the one above?
        new Action<string>(s => this.work.DoStuff(s)).BeginInvoke(hello, null, null);
    }
}

Is (1) an acceptable way of easy starting some work in a seperate thread? If not a better alternative would be much appreciated.

Is (2) doing the same? I guess what I ask is if a new thread is started, or..

Hope you can help a beginner to a better understanding :)

/Moberg

Moberg
  • 783
  • 1
  • 8
  • 17
  • 2
    There is a great article here: http://ondotnet.com/pub/a/dotnet/2003/02/24/asyncdelegates.html that explains the nuances between Threads and asynchronous delegates. – Joseph Yaduvanshi Apr 22 '10 at 14:59
  • Using something as expensive as a thread and then wasting it away with Thread.Join is *not* acceptable. There are many resources to help you choose between Thread and a threadpool thread. – Hans Passant Apr 22 '10 at 15:38

1 Answers1

9

(1) is not an ugly hack, but it is not "the" way of doing threads these days. Thread Pool threads via BeginInvoke/EndInvoke, BackgroundWorker and the Task Parallel Library in .NET 4.0 are the way to go.

(2) is good, BUT you need to pair your BeginInvoke with an EndInvoke somewhere. Assign the new Action<string> to a variable and then call x.EndInvoke() manually on it in your main thread or in a completion method (2nd parameter to BeginInvoke). See here as a decent reference.

Edit: here's how (2) should look to be reasonably equivalent to (1):

    var thread2 = new Action<string>(this.work.DoStuff);
    var result = thread2.BeginInvoke(hello, null, null);
    thread2.EndInvoke(result);
Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87