C # thread series tutorial (1): begininvoke and endinvoke Methods

Source: Internet
Author: User

Author: Galaxy messenger

1. Use the ininvoke and endinvoke methods of the Delegate (delegate) to operate the thread

There are many ways to use threads in C #. One of them is to use the delegate begininvoke and endinvoke methods. The begininvoke method can use threads to asynchronously execute the methods pointed to by the delegate.

Then obtain the return value of the method through the endinvoke method (the return value of the envinvoke method is the return value of the called method), or determine whether the method has been successfully called. We can obtain the return value from the endinvoke method in four ways.

1. Use the endinvoke method directly to obtain the returned value.

When begininvoke is used to call a method asynchronously, if the method is not executed, the endinvoke method will be blocked until the method is executed. See the followingCode

 Using  System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using System. Threading;

Namespace Leleapplication1
{
Class Program
{
Private Static Int Newtask ( Int MS)
{
Console. writeline (
" Task execution started " );
Thread. Sleep (MS );
Random random
= New Random ();
Int N = Random. Next ( 100000 );
Console. writeline (
" Task completed " );
Return N;
}

Delegate Int Newtaskdeletegate ( Int MS );
Static Void Main ( String [] ARGs)
{
Newtaskdeletegate task
= Newtask;
Iasyncresult asyncresult
= Task. begininvoke ( 2000 , Null , Null );

// The endinvoke method will be blocked for 2 seconds.
Int Result = Task. endinvoke (asyncresult );
Console. writeline (result );
Console. Readline ();

}
}
}

InProgramBecause the newtask method delay by sleep for 2 seconds, the program will not output the final result until 2 seconds. If you do not call the endinvoke method, the program will immediately execute it. This is because all the threads created using begininvoke are background threads, once all the front-end threads exit (one of the main threads is the front-end thread), the thread ends regardless of whether the execution of the background thread is complete.

You can use the above program to perform an experiment: firstAdd the following code to the beginning of the method:

Thread. Sleep (10000 );

To enableMainMethod Delay10Second, execute the following code, and then pressCTRL + F5Run the program, open the Enterprise Manager, and observe the number of threads of the current program. Assume that the number of threads is4, In10The number of threads increases5This is becauseBegininvokeA thread is created for asynchronous execution.NewtaskMethod. Therefore, a thread is added.

2. Use the iasyncresult asyncresult attribute to determine whether the asynchronous call is complete.

Although the above method can be used to implement asynchronous calls, when the endinvoke method is used to obtain the call result monotonically, the entire program is like dead. This makes the user feel bad. Therefore, we can use asyncresult to determine whether the asynchronous call is complete and display some prompts. This will increase the user experience. The Code is as follows:

   Static    Void  Main (  String  [] ARGs)
{
Newtaskdeletegate task
= Newtask;
Iasyncresult asyncresult
= Task. begininvoke ( 2000 , Null , Null );

While ( ! Asyncresult. iscompleted)
{
Console. writeline (
" Executing. Please wait... " );
Thread. Sleep (
100 );
}

// The endinvoke method will be blocked for 2 seconds.
Int Result = Task. endinvoke (asyncresult );
Console. writeline (result );
Console. Readline ();

}

3. Use the waitone method to wait for the Asynchronous Method to complete.

The waitone method is another way to determine whether the Asynchronous Method is complete. The Code is as follows:

 Static     Void  Main (  String  [] ARGs)
{
Newtaskdeletegate task
= Newtask;
Iasyncresult asyncresult
= Task. begininvoke ( 2000 , Null , Null );

While ( ! Asyncresult. asyncwaithandle. waitone ( 500 , False ))
{
Console. Write (
" * " );
}

Int Result = Task. endinvoke (asyncresult );
Console. writeline (result );

Console. Readline ();
}

The first parameter of waitone indicates the number of milliseconds to wait. within the specified time, the waitone method waits until the asynchronous call is completed and the waitone method is notified to return true. When the time has passed, asynchronous execution has not been completed. The waitone method returns false. If the specified time is 0, it means no waiting. If it is-1, it means waiting forever until the asynchronous call is completed.

4. Use the callback method to return the structure.

The methods described above are actually only equivalent to one method. Although these methods can successfully return results, they can also give users some prompts, but in this process, the whole program is like dead (if you use these methods in Gui programs, it will be very obvious ). If the program can still do other work normally during the call process, it must use the asynchronous call method. Let's write an example of a GUI program. The Code is as follows:

    Private    Delegate     Int  Mymethod ();
Private Int Method ()
{
Thread. Sleep (
10000 );
Return 100 ;
}
Private Void Methodcompleted (iasyncresult asyncresult)
{
If (Asyncresult = Null ) Return ;
Textbox1.text
= (Asyncresult. asyncstate As Mymethod). endinvoke (asyncresult). tostring ();
}
Private Void Btnlogin_click ( Object Sender, eventargs E)
{
Mymethod my
= Method;
Iasyncresult asyncresult
= My. begininvoke (methodcompleted, my );
}

note that the last two parameters of the begininvoke method are used here (if the called method contains parameters, these parameters are used as the first part of begininvoke. If there is no parameter, begininvoke has only two parameters ). The first parameter is the delegate type of the callback method. This delegate has only one parameter, iasyncresult, as shown in methodcompleted. After the method is executed, the system automatically calls the methodcompleted method. The second parameter of begininvoke needs to pass some values to the methodcompleted method. Generally, you can pass the delegate of the called method, as shown in my. This value can be obtained using the iasyncresult. asyncstate attribute.

 Because the above Code accessesFormOne onTextboxTherefore, you needCTRL + F5Run the program (you cannot directly PressF5Run the program. Otherwise, the program cannot be accessed in other threads.Textbox,GuiComponents, and detailed descriptions in the following sections ). AndFormAnd then clickButton1Other controls can still be used, just as nothing has happened.10Seconds laterTextbox1Output100.

7. Other componentsBeginxxxAndEndxxxMethod

In other. NetSimilar ComponentsBegininvokeAndEndinvokeFor exampleSystem. net. httpwebrequestClassBegingetresponseAndEndgetresponseThe following is an example of using these two methods:

 

Private   Void Requestcompleted (iasyncresult asyncresult)
{
If (Asyncresult =   Null ) Return ;
System. net. httpwebrequest HWR
= Asyncresult. asyncstate As System. net. httpwebrequest;
System. net. httpwebresponse response
=  
(System. net. httpwebresponse) HWR. endgetresponse (asyncresult );
System. Io. streamreader SR
=   New  
System. Io. streamreader (response. getresponsestream ());
Textbox1.text
= Sr. readtoend ();
}
Private   Delegate System. net. httpwebresponse requestdelegate (system. net. httpwebrequest request );

private void button#click ( Object sender, eventargs e)
{< br> system. net. httpwebrequest request
=
(system. net. httpwebrequest) system. net. webrequest. create (
" http://www.cnblogs.com " );
iasyncresult asyncresult
= request. begingetresponse (requestcompleted, request);
}

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.