Asynchronous programming mode

Source: Internet
Author: User

1. synchronous and asynchronous execution of the program

2. Wait until the asynchronous call is completed

3. Exceptions in asynchronous calls

4. components that implement the iasyncresult asynchronous call mode

 

 

1.ProgramSynchronous and asynchronous execution

In many programsCodeIt is executed in sequence. If a method is called in the code, you must wait until all the code of this method is executed before you can return to the original place to execute the next line of code, this program running method is called Synchronization

Sample program

Class Program

{

Static void main (string [] ARGs)

{

Long size;

String foldname;

Console. writeline ("Enter the folder name :");

Foldname = console. Readline ();

Size = calculatefoldersize (foldname );

Console. writeline ("folder {0} capacity: {1}", foldname, size );

Console. readkey ();

}

Public static long calculatefoldersize (string Foldername)

{

If (directory. exists (Foldername ))

{

New exception ("Folder does not exist ");

}

Directoryinfo direroot = new directoryinfo (Foldername );

Directoryinfo [] dire = direroot. getdirectories ();

Fileinfo [] file = direroot. getfiles ();

Long size = 0;

Foreach (var f in file)

{

Size + = f. length;

}

Foreach (var d in dire)

{

Size + = calculatefoldersize (D. fullname );

}

Return size;

}

}

Execution result:

Note:Size = calculatefoldersize (foldname). If this method is not returned, the first sentence cannot be executed.

If it takes some time for the calculatefolder method to be executed (the layers are deep and there are many files), the user will not see the task information before the method returns, and may crash.

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.

Modify the method in the above Code main and implement it using Delegation

Public Delegate long calculatefoldersizedelegate (string Foldername );

Static void main (string [] ARGs)
{
Calculatefoldersizedelegate d = calculatefoldersize;
Console. writeline ("enter a number :");
String foldname = console. Readline ();
Iasyncresult ret = D. begininvoke (foldname, null, null );
Console. writeline ("computing in progress, please wait ");
Long size = D. endinvoke (RET );
Console. writeline ("computing completed, folder {0} capacity is {1}", foldname, size );
Console. readkey ();
}

Execution result:

Note: After calculatefoldersize is executed, the system does not wait for it to complete. Instead, it immediately runs the following statement and outputs a prompt message, "computing in progress. Please be patient ".

In the above Code, iasyncresult ret = D. begininvoke (foldname, null, null );

Call the static method calculatefoldersize indirectly by entrusting the begininvoke method of the image D. This is an asynchronous call.

The key to asynchronous calling is that the static method calculatefoldersize is not executed in the main thread (that is, the main method), but is executed in parallel with the main thread code in another auxiliary thread, because there are two parallel execution threads, after the static execution is started, you must have a way to retrieve the computing result. The endinvoke method can complete this task, but it requires some additional information, this information is provided when the begininvoke method starts asynchronous calls. This is the returned value of the begininvoke method ret, an iasyncresult type object, which will become a parameter of the endinvoke method.

When the endinvoke method is executed, if the calcuatefoldersize method has not been returned, it will stop waiting.

 

2. Wait until the asynchronous call is completed

In the above asynchronous call example, the user only sees a fixed message: "computing is in progress. Please wait .....", Without the following content, the interaction is obviously not very good. Although the window applications with visual forms cannot be as rich as they are, it is still possible to make a small improvement, we can let the computer output a small point to the console at intervals (for example, 2 seconds) during the asynchronous call of the program, telling the user that the search is in progress, this greatly improves the user friendliness of the program,

Public Delegate long calculatefoldersizedelegate (string Foldername );
Static void main (string [] ARGs)
{
Long size = 0;
Calculatefoldersizedelegate d = calculatefoldersize;
Console. writeline ("enter a file name ");
String foldname = console. Readline ();
Iasyncresult ret = D. begininvoke (foldname, null, null );
Console. writeline ("computing in progress, please wait ");
While (Ret. iscompleted = false)
{
Console. Write (".");
System. Threading. thread. Sleep (2000 );
}
Size = D. endinvoke (RET );
Console. writeline ("computing completed, folder {0} capacity is {1}", foldname, size );
Console. readkey ();
}

The iscompleted attribute value method constantly asks whether the asynchronous call is complete. You can also use the asyncwaithandle attribute provided by iasyncresult.

Now, it is better to judge whether asynchronous execution is complete every two seconds and output a small point without completion. However, this will undoubtedly waste a lot of CPU time on the loop wait, can I enable the asynchronous call method to automatically call a method at the end and display the processing result in this method?

In this case, you can use a remote callback. The last two parameters in the begininvoke method definition are asynccallback callback and object asyncstate, which are used for asynchronous calls.

Further improve the program so that you can enter Multiple folder names consecutively. The computer calculates the names separately in the background and then outputs the results in the console window.

Example:

Public Delegate long calculatefoldersizedelegate (string foldname );

Private Static calculatefoldersizedelegate d = calculatefoldersize;

Static void main (string [] ARGs)

{

String foldname = "";

While (true)

{

Console. writeline ("Enter the folder name and enter the quit program ");

Foldname = console. Readline ();

If (foldname = "quit ")

Break;

D. begininvoke (foldname, showfoldersize, foldname );

}

}

Public static void showfoldersize (iasyncresult result)

{

Long size = D. endinvoke (result );

Console. writeline ("Computation complete, folder {0} capacity is {1}", result. asyncstate. tostring (), size );

}

Execution result:

The first task is not necessarily completed first, because if the subsequent task has a low workload, the execution is completed first.

Note This sentence D. begininvoke (foldname, showfoldersize, foldname)

The first parameter of the begininvoke method specifies that the showfoldersize method is called back when the asynchronous call ends. The first parameter asyncstate is filled with the name of the folder to be calculated, this value is encapsulated by the begininvoke method into an iasyncresult type object that is automatically created and automatically transmitted to the callback method as a method real parameter, the callback method obtains the value through the asyncstate field of this real parameter.

 

3. Exceptions in asynchronous calls

The exception handling method in synchronization mode is to use try and catch to handle exceptions in the code that calls this method. Because the Exception Code is located in the same thread as the call code, when an exception occurs, the computer will interrupt the execution process of the current thread and forward it to the execution of the Exception Processing code.

But how can I handle exceptions in the asynchronous call process?

When an Asynchronous Method throws an exception, CRL will capture it. When the asynchronous call thread starts to call the endinvoke method and waits for the end of the asynchronous call, CLR will throw this exception again, in this way, the caller thread can capture it.

If a callback method is provided when the begininvoke method is called to start asynchronous calls, the CLR will immediately call the method to be called after an exception thrown by the method is caught, the callback method usually needs to call the endinvoke method.

In short, the asynchronous call exception can be captured in the Code where the endinvoke method is located.

Example:

Public static void showfoldersize (iasyncresult result)

{

Try

{

Long size = D. endinvoke (result );

Console. writeline ("the size of the folder {0} is {1} bytes \ n", (string) result. asyncstate, size );

 

}

Catch (directorynotfoundexception E)

{

Console. writeline (E. tostring ());

}

 

}

4. components that implement the iasyncresult asynchronous call mode

In the. NET base class library, some current components directly implement the iasyncresult asynchronous call design mode. These components usually provide synchronous and asynchronous calls to a method at the same time.

The webrequest in the system. Net namespace shows the methods,

After careful analysis, we will find that there are some rules.

1. There is a begin method with a corresponding end Method

2. Each begin/end method has a corresponding synchronization method, for example, begingetresponse/endgetresponse getresponse ()

3. The end method and the corresponding synchronous method return value are of the same type.

The begin method returns an iasyncresult object, while the end method parameters receive this object. This mode is almost the same as the delegate-based Asynchronous call mode.

For the sample code, see the following: implement the function and use Asynchronous callback to notify the user that the file has been downloaded.

Class Program

{

Static void main (string [] ARGs)

{

String inputurl = "";

String filename = "";

Console. writeline ("enter a URL to start the asynchronous file download task ");

Do

{

Console. writeline ("Enter Web file ");

Inputurl = console. Readline ();

If (string. isnullorempty (inputurl ))

{

Console. writeline ("URL cannot enter an empty string ");

Continue;

}

Console. writeline ("Enter the file name to save ");

Filename = console. Readline ();

If (string. isnullorempty (filename ))

{

Console. writeline ("file name cannot be blank ");

Continue;

}

If (inputurl = "quit" | filename = "quit ")

{

Break;

}

Try

{

Uri weburi = new uri (inputurl );

Webrequest = webrequest. Create (weburi );

Downloadtask d = new downloadtask {webrequestobj = webrequest, savefilename = filename };

Console. writeline ("{0} has been started in the background and saved as {1}", inputurl, filename );

Webrequest. begingetresponse (downloadfinished, d );

}

Catch (exception ex)

{

Console. writeline (ex. tostring ());

}

} While (true );

}

Static void downloadfinished (iasyncresult OBJ)

{

Downloadtask d = obj. asyncstate as downloadtask;

Webresponse = D. webrequestobj. endgetresponse (OBJ );

String filecontent = "";

Using (streamreader reader = new streamreader (webresponse. getresponsestream (), encoding. getencoding ("gb2312 ")))

{

Filecontent = reader. readtoend ();

}

Using (streamwriter write = new streamwriter (New filestream (D. savefilename, filemode. Create), encoding. getencoding ("gb2312 ")))

{

Write. Write (filecontent );

}

MessageBox. Show (string. Format ("{0} download completed", D. savefilename ));

}

}

Public class downloadtask

{

Public webrequest webrequestobj {Get; set ;}

Public String savefilename {Get; set ;}

}

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.