I have an event delegate that is defined as follows:
public delegate void CallbackDelegate(Data data);
public event CallbackDelegate OnDataComplete;
I raise the event asynchronously:
// Raise the OnDataComplete event
OnDataComplete.BeginInvoke(new Data(), null, null);
Subsequently, the signature of BeginInvoke
looks like:
IAsyncResult CallbackDelegate.BeginInvoke(Data data, AsyncCallback callback, object @object)
In most examples I've seen BeginInvoke
is called with the @object
parameter being null
, but I can't find the documentation which explains what is the purpose of that parameter.
So what is the purpose of that parameter? What can we use it for?
You can provide anything you want there. In the AsyncResult method you can retrieve this value with IAsyncResult.AsyncState. It's there for your use.
It's so that you can pass any relevant information from your method to the callback. Since C# has lambda expressions and since delegates can have state, sometimes this is useless, and you can just pass null. But it's a bit similar to Control.Tag
, and it lets you give information to the callback that it might find handy.
Update:
The origin of why it even exists goes back to languages that only had function pointers, with no closure. (You might want to look up the word "closure"... I can't explain it very concisely.) In C, there's only function pointers and not delegates; hence, function pointers can't hold state. So whenever you provided a callback, the callee helped you by passing an additional pointer for you, so you could pass data to your callback that it might need. In .NET, these are less necessary (because delegates have Target
objects and can hold state), but sometimes they're handy and that's where they come from.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With