Delegate and asynchronous operations

Source: Internet
Author: User

A delegate is a type that stores the reference as a function. The delegate declaration is a very type function, but it does not contain a function body and uses delegate. The delegate Declaration refers

A function signature is set, which contains a list of return types and parameters. After the delegate is defined, the variable of the delegate type can be declared, and then the variable is initialized.

Reference a function with the same signature as the delegate. Then you can use the delegate variable to call this function.
The delegate is just a function pointer, that is, it can reference the function and complete it through the address transfer mechanism. A delegate is a class. When you instantiate it

Used as a parameter of the constructor.
As a function pointer, delegates can associate an event with a function to execute the Connected Function once an event occurs.

 

 

 

 

Http://www.cnblogs.com/einsteinlu

Control. Invoke method (delegate): executes the specified delegate on the thread that owns the basic window handle of this control.

Control. begininvoke method (delegate): executes the specified delegate asynchronously on the thread where the basic handle of the control is created.

The following are the problems encountered in actual application. Start a thread in the main thread and start serviceform in this thread. However, after the thread is started

Serviceform sends commands. serviceform. ishandlecreated always reports serviceform = NULL and cannot execute commands. You can solve this problem by using a delay method.

This problem was solved, but it was not an efficient solution. Later, in serviceform. Load + = new eventhandler (serviceform_load); serviceform_load

And sent successfully. The main cause is multithreading.

Satirserviceform serviceform;
Thread serviceformthread;

Protected void Init ()
{
Serviceformthread = new thread (mainformmessagethread );
Serviceformthread. Name = "servicethread ";
Serviceformthread. Start ();
}

Protected void mainformmessagethread ()
{
If (serviceform = NULL)
{
Serviceform = new satirserviceform ();
Serviceform. Load + = new eventhandler (serviceform_load );
// Serviceform. recvedcmd + = new eventhandler (onservicerecvedcmd );

}
Application. Run (serviceform );
}

Void serviceform_load (Object sender, eventargs E)
{
Sendcommand (infraonlinecmd. Start, 0 );
Sendcommand (infraonlinecmd. autoajust, 0 );
}

Protected override void sendcommand (infraonlinecmd cmd, object PARAM)
{
If (Param! = NULL & Param is int)
This. Param = (INT) Param;

If (serviceform. ishandlecreated)
{
Serviceform. begininvoke (New dcmdhandler (executecmd), CMD );
}
}

The following ZT from: http://blog.163.com/kjpt126@126/blog/static/48940426200824103658846/

Control invoke and begininvoke

Recently, the invoke and begininvoke involved a huge number of tasks, so I checked some relevant information and sorted it out as follows. Thanks for thisArticleMy understanding of invoke and

The true meaning of begininvoke.

(1) control invoke and begininvoke

Based on the following knowledge:

(1) The invoke and begininvoke of control are different from those of delegate.

(2) The parameters of control invoke and begininvoke are delegate. The delegate method is executed on the control thread, which is what we usually call

Ui thread.

We useCode(1) view (control invoke)

Private delegate void invokedelegate ();

Private void invokemethod (){

// C code segment

}

Private void butinvoke_click (Object sender, eventargs e ){

// A code snippet .......

This. Invoke (New invokedelegate (invokemethod ));

// B code segment ......

}

What do you think is the code execution sequence? Remember that the invoke and begininvoke of control are executed on the main thread, that is, the UI thread.

A ------> C ----------------> B

Explanation: (1) After a finishes executing on the UI thread, start invoke. Invoke is synchronous.

(2) code segment B does not execute, but immediately executes the invokemethod method on the UI thread, that is, code segment C.

(3) After the invokemethod method is executed, code segment C continues to be executed on the UI thread.

Check out the code (2) and control begininvoke

Private delegate void begininvokedelegate ();

Private void begininvokemethod (){

// C code segment

}

Private void butbegininvoke_click (Object sender, eventargs e ){

// A code snippet .......

This. begininvoke (New begininvokedelegate (begininvokemethod ));

// B code segment ......

}

What do you think is the code execution sequence? Remember that the invoke and begininvoke of control are executed on the main thread, that is, the UI thread.

A -----------> B ---------------> C. Be careful. This is only for reference... I'm not sure about the execution sequence. If anyone knows it, please let me know.

Knowledge.

Explanation: (1) After a finishes executing on the UI thread, begininvoke starts and begininvoke is asynchronous.

(2) invokemethod method, that is, code segment C is not executed, but B is executed on the UI thread immediately.

(3) After code segment B is executed (that is, after the butbegininvoke_click method is executed), The invokemethod method, that is, code segment C, continues to be executed on the UI thread.

.

Therefore, we know that:

The delegate methods of control invoke and begininvoke are executed on the main thread, that is, the UI thread. That is to say, if your delegate method is used to take the time

Do not call control. invoke and control. begininvoke on the UI thread, because these are still blocking the UI.

Thread.

So what does Asynchronization mean?

Asynchronization refers to the process of Asynchronization relative to the thread that calls begininvoke, rather than the UI thread. You can call begininvoke on the UI thread, but of course not.

---- This is a comment from "The true meanings of invoke and begininvoke.

The begininvoke principle is to convert the called method into a message, and then call registerwindowmessage () in Win32 API to send a message to the UI window.

. ---- This is a comment from "The true meanings of invoke and begininvoke.

(2) We Use thread to call begininvoke and invoke

We open a thread to let the thread execute some time-consuming operations, and then return to the user UI with control. invoke and control. begininvoke.

Thread to execute interface updates.

Code (3) thread calls the control invoke

Private thread invokethread;

Private delegate void invokedelegate ();

Private void startmethod (){

// C code segment ......

Control. Invoke (New invokedelegate (invokemethod ));

// D code segment ......

}

Private void invokemethod (){

// Ecode segment

}

Private void butinvoke_click (Object sender, eventargs e ){

// A code snippet .......

Invokethread = new thread (New threadstart (startmethod ));

Invokethread. Start ();

// B code segment ......

}

What do you think is the code execution sequence? Remember that the invoke and begininvoke of control are executed on the main thread, that is, the UI thread.

A ------> (start starts with C of B and startmethod at the same time) ----> (C is finished, no matter whether B is finished or not, invokethread mails the message

(Invoke) to the UI thread, and then wait for it) ----> after the UI thread finishes processing the butinvoke_click message, it processes the message sent by invokethread and runs

Invokemethod method, that is, code segment E. After processing, the UI thread switches to the invokethread thread.

This control. Invoke is synchronized with the invokethread thread and stops it from running.

 

Explanation:

1. Ui execution

2. The UI open thread invokethread, B and C are executed simultaneously, B is executed on the thread UI, and C is executed on the thread invokethread.

3. Invokethread sends messages to the UI and waits for them. After the UI finishes processing the messages, it processes the messages sent by invokethread, that is, the code segment E

4. After the UI executes e, it is transferred to the invokethread thread. The invokethread thread executes the code segment D.

Code (4) thread calls the begininvoke of control

Private thread begininvokethread;

Private delegate void begininvokedelegate ();

Private void startmethod (){

// C code segment ......

Control. begininvoke (New begininvokedelegate (begininvokemethod ));

// D code segment ......

}

Private void begininvokemethod (){

// Ecode segment

}

Private void butbegininvoke_click (Object sender, eventargs e ){

// A code snippet .......

Begininvokethread = new thread (New threadstart (startmethod ));

Begininvokethread. Start ();

// B code segment ......

}

What do you think is the code execution sequence? Remember that the invoke and begininvoke of control are executed on the main thread, that is, the UI thread.

A is executed on the UI thread -----> begininvokethread is executed on the thread, UI continues to execute code segment B, and invokethread concurrently executes code segment C ------

--------> No matter whether or not the UI has executed code segment B, the begininvokethread thread sends the message to the UI and does not wait for it. Continue to execute-

-------> After the UI processes the butbegininvoke_click message, it processes the messages sent from the begininvokethread thread.

 

Explanation:

1. Ui execution

2. The UI open thread begininvokethread, B and C are executed simultaneously, B is executed on the thread UI, and C is executed on the begininvokethread thread.

3. Begininvokethread sends messages to the UI, and then executes code D. After the UI finishes processing the messages, it processes the messages sent by invokethread, that is, the code.

Section E

A bit of doubt: if the UI is executed first, is it possible that the message will be sent to the UI only after a period of time begininvokethread, and then the UI will continue to execute the mails

Message E. The light green part.

The begininvoke of control is relative to the thread that calls it, that is, begininvokethread is asynchronous.

Therefore, we can think of it. To asynchronously retrieve long-time data, such as reading a large amount of data from the database, we should do this.

(1) If you want to block the calling thread, call code (3), code segment D is deleted, and C is changed to an operation that takes a long time, because this operation is performed in another thread.

. Code snippet e is used to update the interface.

(2) If you do not want to block the calling thread, call code (4), code segment D is deleted, and C is changed to an operation that takes a long time, because this operation is on another line

. Code snippet e is used to update the interface.

================================
Http://hi.baidu.com/shouxin1014/blog/item/6b6969013022858ae850cd55.html
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. LINQ;
Using system. text;
Using system. Windows. forms;

Namespace callbacktest
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}

// Asynchronous Method
Private string methodname (INT num, out int ret)
{
Ret = num;
Return "helloworld ";
}

// Define the delegate with the same signature as the method
Private delegate string delegatename (INT num, out int ret );

// Callback method (the method to be executed when asynchronous completion is completed. This method only has one iasyncresult parameter, but this parameter is almost omnipotent and can be passed

Object)
Private void callbackmethod (iasyncresult AR)
{
Delegatename DN = (delegatename) Ar. asyncstate;

Int I;

String r = DN. endinvoke (Out I, AR); // be sure to use endinvoke; otherwise, your end is miserable.
MessageBox. Show ("Asynchronous! The value of I is "+ I. tostring () +", and the value of R is "+ r );
}

Private void form1_load (Object sender, eventargs E)
{
// Instantiate the delegate and assign a value first
Delegatename DN = new delegatename (methodname );
Int I;
// Instantiate the callback function and regard asynccallback as delegate. In fact, asynccallback is a special delegate.

 
Asynccallback ACB = new asynccallback (callbackmethod );
// Asynchronous Start
// If the value of ACB is null, no callback method is available.
// Place where the last parameter dn can be changed to any object, which can be obtained by the callback method from the parameter and written as null.

.
// The parameter dn is equivalent to the thread ID. If multiple asynchronous threads exist, they can all be null, but they cannot be the same.

Object. Otherwise, an exception occurs.
Iasyncresult IAR = DN. begininvoke (1, out I, ACB, DN );
}
}
}

 

 

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.