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
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 .
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 .
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) 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With