开发者

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?


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.


That's just a state object that ends up in IAsyncResult.AsyncState that can be retrieved in your AsyncCallback code. Kinda like the ThreadPool.QueueWorkItem(WaitCallback, Object).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜