C # general procedure for callback implementations
The method callback mechanism of C # is built on the basis of the delegate, and the typical implementation process is given below.
(i) defining, declaring callbacks
Delegate void Dosomecallback (type para);
Dosomecallback Dosomecallback;
As you can see, the "callback" (Dosomecallback) defining the declaration here is actually a delegate.
(ii) Initialize the callback method
Dosomecallback=new Dosomecallback (Dosomemethod);
The so-called "Initialize callback method" is actually instantiating a delegate that has just been defined, where the Dosomemethod as a parameter is called a "callback method" that encapsulates the operation code of the target object (form control or other class) in another thread.
(iii) Trigger object action
Opt obj. Invoke (DOSOMECALLBACK,ARG);
where Opt obj is the target operand, assuming that he is a control, call its Invoke method. The signature of the Invoke method is:
- Object Control. Invoke (Delegate method,params object[] args)
Its first argument is the delegate type, and the essence of the "Trigger object action" is to pass the delegate dosomecallback as a parameter to the control's Invoke method, which is exactly the same as the delegate's usage.
The code that ultimately acts on the object opt obj is placed in the callback method body Dosomemethod (), as follows:
private void Dosomemethod (type para)
{
Opt obj. SomeMethod (para);
}
If the callback is not used, it is used directly in the program "Opt obj. SomeMethod (para);" When the object opt obj is not on this thread (Kua-thread access), the following error occurs: "Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException" An exception to the type or "system.invalidoperationexception; the inter-thread operation is not valid, and it is accessed from a thread that does not create the control. ”
General procedures for C # callback implementations