What should be passed for the BeginInvoke @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 BeginInvoke signature looks like this:

 IAsyncResult CallbackDelegate.BeginInvoke(Data data, AsyncCallback callback, object @object) 

In most examples, I saw that BeginInvoke is called with the @object parameter, which is null , but I can not find the documentation that explains what the purpose of this parameter is.

So what is the purpose of this parameter? What can we use for this?

+8
multithreading c # events begininvoke delegates
source share
3 answers

This is so that you can pass any relevant information from your method to the callback. Since C # has lambda expressions, and since delegates can have a state, it is sometimes useless, and you can just pass null. But it is a bit like Control.Tag , and it allows you to specify a callback that may be convenient.


Update:

The origin of why it exists goes back to languages ​​that only had function pointers, without closure. (You might want to find the word β€œclose” ... I cannot explain this very briefly.) In C, there are only function pointers, not delegates; therefore, function pointers cannot contain state. Therefore, whenever you provided a callback, the caller called you, passing an extra pointer for you so that you can pass the data to your callback, which may be required. In .NET, they are less necessary (because delegates have Target objects and may contain state), but sometimes they are convenient and that they appear.

+8
source share

You can provide whatever you want. In the AsyncResult method, you can get this value using IAsyncResult.AsyncState. This is there for your use.

+8
source share

This is just a state object that ends in IAsyncResult.AsyncState , which can be obtained in AsyncCallback code. Like ThreadPool.QueueWorkItem (WaitCallback, Object) .

+4
source share

Source: https://habr.com/ru/post/651355/


All Articles