difference is between using ThreadStart and delegates instead ofusing BeginInvoke

R

robparr

Hello, hopefully someone can help me.

I am reading and learning steadily about threading and asynchronous
programming, which to me sound like the same thing. At the moment I am
not sure what the difference is between using ThreadStart and
delegates instead of using BeginInvoke. Can both of them be used to
achieve the same thing? Or perhaps you should use one over the other?
I am slightly confused because I was looking at this example from mono
project (http://www.mono-project.com/ThreadsBeginnersGuide)


using System;
using System.Threading;

namespace ThreadGuideSamples {
public delegate void MyCallBack (int Response);

class ThreadCaller {
static void Main () {
ThreadCaller myCaller = new ThreadCaller ();
}

public ThreadCaller () {
// Passing an MyCallBack-Delegate to the object executed on the
// different thread.
SecondThreadObject myThreadObject = new
SecondThreadObject (new MyCallBack(this.OnResponse));

// Starting the thread as usual
Thread myThread = new Thread (new
ThreadStart (myThreadObject.MyAsyncMethod));
myThread.Start ();
}

// Target-Destination for messages from our thread
protected void OnResponse (int response) {
Console.WriteLine ("Value returned to " +
"main thread {0}", response);
}
}

class SecondThreadObject {
protected MyCallBack On_Response = null;

public SecondThreadObject (MyCallBack callback) {
this.On_Response = callback;
}

public void MyAsyncMethod () {
for (int i = 0; i < 50; i++)
if (this.On_Response != null)
// Invoke the call back delegate
this.On_Response (i);
Console.ReadKey ();
}
}
}

I wasn't quite sure why BeginInvoke, EndInvoke and AsyncCallback
delegate werent used.
 
M

Marc Gravell

A few differences... ThreadStart gives you full control of the thread
(rather than the delegate which will probably use a pool-thread [which
is often fine]). Actually, a third comparison might be to
ThreadPool.QueueUserWorkItem.
Also, the callback mechanism is different: with ThreadStart you do it
yourself; with BeginInvoke there is a common pattern (which personally
I don't find very intuitive). But note that this pattern is also often
used with completion port semantics, which abstracts whether you are
waiting on an actual thread, versus IO.

As a fourth thing - watch out for Control.BeginInvoke - the meaning is
different to Delegate.BeginInvoke.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top