views:

161

answers:

4

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?

+1  A: 

You may have multiple threads calling the same delegate instance, as per you wish them all to perform the same task, for instance.

Will Marcouiller
+3  A: 

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.

Jon Skeet
+1  A: 

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.

SLaks
+2  A: 

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)

Simon P Stevens