Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be passed for BeginInvoke's @object parameter?

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?

like image 393
Kiril Avatar asked Jan 21 '11 20:01

Kiril


2 Answers

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.

like image 165
Tergiver Avatar answered Oct 04 '22 02:10

Tergiver


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.

like image 26
user541686 Avatar answered Oct 04 '22 00:10

user541686