简体   繁体   中英

Why can you call BeginInvoke more than once on the same delegate instance?

I thought that calling BeginInvoke more than once on the same delegate instance would cause problems, but I tried it out and it works. Why is that?

Is the IAsyncResult object returned with each BeginInvoke called unique instead of each instance of the delegate?

In other words, do I only need one instance of the delegate to spawn multiple calls to its function?

Why would it not work? Each time you call it, it will start executing that delegate's actions on a threadpool thread. Yes, each IAsyncResult will be independent of the others, representing that asynchronous action.

Yes, you only need one instance of the delegate. Note that delegates are immutable - calling BeginInvoke isn't going to change its state. You can safely take a copy of a delegate reference, safe in the knowledge that calling Delegate.Combine etc will always create a new delegate instance, rather than modifying the existing one.

Each call to BeginInvoke triggers a new request onto the .net thread pool.

It is perfectly acceptable to call BeginInvoke multiple times. Each IAsyncResult object is unique to that specific call to BeginInvoke .

Just be careful to make sure that you make a matching call to EndInvoke for every BeginInvoke call you make to make sure the resources are cleaned up.

(Note that each call does not necessarily equate to a thread. BeginInvoke passes the requests to the thread pool, which may queue up the requests if all of the threads in the pool are already in use)

例如,您可能希望有多个线程调用相同的委托实例,例如,希望它们都执行相同的任务。

Yes.

Each call to BeginInvoke will return a different IAsyncResult , which can be passed to EndInvoke in any order.

You can use the same delegate to make multiple asynchronous calls.

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