Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Thread/BeginInvoke? [beginner]

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

like image 668
Moberg Avatar asked Apr 22 '10 14:04

Moberg


People also ask

How does BeginInvoke work?

BeginInvoke returns immediately and does not wait for the asynchronous call to complete. BeginInvoke returns an IAsyncResult, which can be used to monitor the progress of the asynchronous call. The EndInvoke method retrieves the results of the asynchronous call. It can be called any time after BeginInvoke .

Whats up with BeginInvoke?

What does BeginInvoke do? According to MSDN, Control. BeginInvoke "Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on". It basically takes a delegate and runs it on the thread that created the control on which you called BeginInvoke .

Why use BeginInvoke c#?

You call BeginInvoke if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases. If BeginInvoke is called for Delegate type the delegate is just invoked asynchronously. ( Invoke for the sync version.)


1 Answers

(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);
like image 111
Jesse C. Slicer Avatar answered Oct 06 '22 21:10

Jesse C. Slicer