tags:

views:

73

answers:

3

What is the difference between the following?

public delegate void SetSthDelegate(int[] x);

// 1)
SetSthDelegate sst = new SetSthDelegate(SetSthMethod);
sst(x);

// 2)
Invoke(new SetSthDelegate(SetSthMethod), new object[] {x}

// 3)
BeginInvoke(new SetSthDelegate(SetSthMethod), new object[] {x}

I learned that 2) is for invoking methods synchronously while 3) is for invoking methods asynchronously, but when do you want to invoke methods synchronously and asynchronously?

Can someone show me when an illustration and explanation when to use 1), 2), 3) is more appropriate.

Edit: Can also explain why ppl prefers Invoke over BeingInvoke and visa versa?

A: 

Hi, number 1) and 2) are the same. They invoke the delegate synchronously. Number 3), as you said, invokes it asynchronously. You want to execute a delegate asynchronously in cases when you don't want to lock your thread and wait until the delegate code ends executing. By using beginInvoke the delegate executes in a background thread and your main thread continues executing something.

Here is a detailed explanation: http://blogs.msdn.com/b/thottams/archive/2007/11/01/calling-delegates-using-begininvoke-invoke-dynamicinvoke-and-delegate.aspx

Hope this helps!

Nicolas Bottarini
Enigmativity
hi Enigmativity, u r right it is in a windows form. But then what is the difference in the Windows Forms Control's Invoke method that is being called vs the SetSthDelegate delegate's Invoke method being called? It seems that the code is still being able to be execute.
yeeen
@yeeen: Control.Invoke (http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx) executes the delegate on the UI thread (that is the thread the control was created on). You can safely access the control only from the UI thread, so if you are on a different thread Invoke/BeginInvoke should be used.
Patko
A: 

The main reason for using BeginInvoke is if the operation will take time. Then you probably don't want to block the invoker and just be notified when it is finished. It adds complications to the code, so you probably don't want to do it if you don't need it.

If the operation is quick, you probably don't want to complicate the code with asynchronous calls. Also, if this operation really requires that the caller waits for the answer, then a synchronous may be as good. It all depends...

Philippe Lignon
A: 
  • invoke is similar to normal method calling.
  • BeginInvoke() or asunc invoke is just call then go. u dont want to wait for the work to be done or it is slow work and not neccessary to wait 1) and 2) is the same thing. but 3) is asynchronous invoke

in my app when i want to send email or log something i use BeginInvoke becus it's not neccessary to wait

888