Reputation: 2177
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?
Upvotes: 2
Views: 1836
Reputation: 27509
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)
Upvotes: 3
Reputation: 888067
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.
Upvotes: 1
Reputation: 1503180
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.
Upvotes: 3
Reputation: 24142
You may have multiple threads calling the same delegate instance, as per you wish them all to perform the same task, for instance.
Upvotes: 1