(2) thread-call Methods asynchronously through delegation (sample download)

Source: Internet
Author: User

(1). Description
First, run a simple thread example to understand the thread.
Determine the thread status through Delegate call method and asyncresult

(2). Code
Using system;
Using system. Threading;
Using system. runtime. remoting. messaging;

Namespace uses the delegate asynchronous call Method
{
// Delegate Declaration (function signature)
Delegate string mymethoddelegate ();

Class myclass
{
// Dynamic method to be called
Public String mymethod1 ()
{
Return "Hello word1 ";
}

// Static method to be called
Public static string mymethod2 ()
{
Return "Hello word2 ";
}
}
Class class1
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main (string [] ARGs)
{
Myclass = new myclass ();

// Method 1: declare the delegate and call mymethod1
Mymethoddelegate d = new mymethoddelegate (myclass. mymethod1 );
String strend = D ();
Console. writeline (strend );

// Method 2: declare the delegate and call mymethod2 (using the asyncresult object)
D = new mymethoddelegate (myclass. mymethod2); // defines a delegate that can be used by multiple methods
Asyncresult myresult; // the result of the asynchronous call of this type of closed asynchronous delegation is obtained through asyncresult.
Myresult = (asyncresult) D. begininvoke (null, null); // start to call
While (! Myresult. iscompleted) // determines whether the thread execution is complete.
{
Console. writeline ("Asynchronous execution of mymethod2 .....");
}
Console. writeline ("method mymethod2 execution completed! ");
Strend = D. endinvoke (myresult); // wait until the method called by the delegate is completed and return the result
Console. writeline (strend );
Console. Read ();
}
}
}

The code in this example has been tested and runs properly!

(3) Sample download
Http://www.cnblogs.com/Files/ChengKing/ThreadExample.rar

 

Related Article

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.