简体   繁体   中英

Difference between different ways to invoke a delegate

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?

Can also explain why people prefer Invoke over BeingInvoke and visa versa?

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!

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...

  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM