General procedures for C # callback implementations

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.