(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