views:

132

answers:

1

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

+2  A: 

(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