Asynchronous programming mode (I)

Source: Internet
Author: User

The asynchronous programming technology of. NET is mainly divided into two parts:

1. Use the asynchronous programming mode of iasyncresult.

2. Event-based asynchronous programming mode.

 

C # the compiler will generate the begininvoke/endinvoke method that supports asynchronous execution for each delegate, so as to closely associate the delegate with asynchronous programming.

 

When synchronous executionProgramIf it takes a long time to executeCodeThe user must wait and think that the program is stuck or dead.

The sample code of the synchronization program is as follows:

 Namespace Calculatefoldersizenoasync
{
Class Program
{
// Calculates the total capacity of a specified folder.
Private Static Long Calculatefoldersize ( String Foldername)
{
If (Directory. exists (Foldername) = False )
{
Throw New Directorynotfoundexception ( " Folder does not exist " );
}

Directoryinfo rootdir =New Directoryinfo (Foldername );
// Get all subfolders
Directoryinfo [] childdirs = rootdir. getdirectories ();
// Get all files in the current folder
Fileinfo [] files = rootdir. getfiles ();
Long Totalsize = 0 ;
// Accumulate the size of each file
Foreach (Fileinfo File In Files)
{
Totalsize + = file. length;
}
// Execute the same calculation process for each folder: Accumulate the size of each file
// This is implemented through recursive calls.
Foreach (Directoryinfo dir In Childdirs)
{
Totalsize + = calculatefoldersize (dir. fullname );
}
// Total size of returned folders
Return Totalsize;
}

Static Void Main ( String [] ARGs)
{
Long Size;
String Foldername;


Console. writeline ( " Enter the folder name (for example, c: \ Windows ): " );

Foldername = console. Readline ();


Size = calculatefoldersize (Foldername );

Console. writeline ( " \ N folder {0} capacity: {1} bytes \ n " , Foldername, size );

Console. readkey ();

}
}
}

The calculatefoldersize method is called in the program. If this method is not returned, the following code cannot be executed.

If the execution of this method takes a long time, the user will not see any information before the method is returned, and he may think that the computer has crashed.

The preceding program is a typical synchronous execution mode.

Can I execute the next statement immediately after the method is called without waiting for the method to be executed to be completed?

To implement this function, you must adopt the "asynchronous programming mode"

 

Example code:

 Namespace Asynccalculatefoldersize1
{
Class Program
{
// Calculates the total capacity of a specified folder.
Private Static Long Calculatefoldersize ( String Foldername)
{
If (Directory. exists (Foldername) = False )
{
Throw New Directorynotfoundexception ( " Folder does not exist " );
}

Directoryinfo rootdir = New Directoryinfo (Foldername );

// Get all subfolders
Directoryinfo [] childdirs = rootdir. getdirectories ();
// Get all files in the current folder
Fileinfo [] files = rootdir. getfiles ();
Long Totalsize = 0 ;
// Accumulate the size of each file
Foreach (Fileinfo File In Files)
{
Totalsize + = file. length;
}
// Execute the same calculation process for each folder: Accumulate the size of each file
// This is implemented through recursive calls.
Foreach (Directoryinfo dir In Childdirs)
{
Totalsize + = calculatefoldersize (dir. fullname );
}
// Total size of returned folders
Return Totalsize;
}

// Define a delegate
Public Delegate Long Calculatefoldersizedelegate ( String Foldername );

Static Void Main ( String [] ARGs)
{

// Define a delegate variable reference static method calculatefoldersize
Calculatefoldersizedelegate d = calculatefoldersize;

Console. writeline ( " Enter the folder name (for example, c: \ Windows ): " );

String Foldername = console. Readline ();

// Call the static method calculatefoldersize asynchronously through delegation
Iasyncresult ret = D. begininvoke (Foldername, Null , Null );

Console. writeline ( " Computing... please wait ...... " );
// Blocking. Wait until the call is complete and retrieve the result.
Long Size = D. endinvoke (RET );

Console. writeline ( " \ N computing is complete. The size of the folder {0} is {1} bytes \ n " , Foldername, size );

Console. readkey ();
}
}


}

The asynchronous programming method in this example is implemented through delegation.

Create a delegate variable d that references the static method calculatefoldersize, and call the static method calculatefoldersize indirectly by calling the ininvoke method of the delegate Object D, which is not executed in the main thread.

In the other secondary pub program, the code is executed in parallel with the main thread. Because there are two parallel threads, after the static method calculatefildersize is started, it will not wait until it is completed, instead, execute the next sentence immediately.

A prompt message is displayed.

 

From this typical asynchronous calling program, we can know that a common programming mode of asynchronous calling is:

//..............

// Common code: In synchronous Execution Mode

Iasyncresult ret = delegate variable. begininvoke (...); // start asynchronous call

// You can do other things in this part, and the program is in asynchronous execution mode.

Variable used to save the Method Result = delegate variable. endinvoke (RET); // end asynchronous call

// Common code: In synchronous Execution Mode

//...............

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.