Asynchronous programming mode (6): Event-based Asynchronous calling Mode

Source: Internet
Author: User

The previous diary introduced the components that support the iasyncresult asynchronous call mode represented by webresponse. Some components in the. net base class library implement another asynchronous mode,

This is "Event-based asynchronous mode (EAP mode )".

 

The most typical component that implements the EAP mode is WebClient.

WebClient defines the following two Synchronization Methods for downloading files from the Web:

 
Public VoidDownloadfile (StringAddress,StringFilename );

Public VoidDownloadfile (URI address,StringFilename );

To Implement Asynchronous calls, WebClient defines two other asynchronous methods:

Public VoidDownloadfileasync (URI address,StringFilename );

Public VoidDownloadfileasync (URI address,StringFilename,ObjectUsertoken );

EAP specifies that the method name ending with async is an asynchronous call method.

 

In the preceding method, the role of the last usertoken parameter is described earlier.

It is actually very simple, when the applicationProgramThis parameter is used to differentiate multiple asynchronous download tasks when multiple asynchronous download tasks are started by calling the downloadfileasync method for multiple times. Simply put,Usertoken

Is the identifier of the asynchronous download task. It is the programmer's responsibility to provide a unique identifier for each ongoing download task.

 

To cancel a task midway through, WebClient defines the following methods:

Public void cancelasync ();

The task can be canceled, so the problem arises: After the asynchronous call method is started, how does the caller know whether the task is terminated normally or canceled midway through?

The answer is simple: when the asynchronous call task ends, the component that implements EAP will trigger a corresponding event. Taking WebClient as an example, when the asynchronous download task started by the downloadfileasync method ends, it will trigger the following events:

Public event asynccompletedeventhandler downloadfilecompleted;

This event has an asynccompletedeventargs parameter, which contains important information:

  Public   class  asynccompletedeventargs: eventargs 
{< br> Public bool cancelled { Get ;}< span style =" color: #008000; ">/// This value indicates whether the asynchronous operation has been canceled.

Public Exception error { Get ;}< span style =" color: #008000; ">/// This value indicates an error occurred during an asynchronous operation.

Public Object userstate { Get ;}< span style =" color: #008000; ">/// obtain the unique identifier of an asynchronous task. If you set a task identifier when starting this task, this attribute value is the identifier

}

Therefore, you only need to check the cancelled attribute of the event parameter in the response method of the downloadfilecompleted event. If the value is true, the task is canceled midway through.

If the error attribute is not null, an exception is thrown during task execution. If neither of the preceding conditions is met, the task is successfully completed.

When an asynchronous task may take a long time to execute, you must be notified of the progress of the current job. Therefore, WebClient defines the following events:

Public event downloadprogresschangedeventhandler downloadprogresschanged;

This event parameter contains important information (downloadprogresschangedeventargs type objects.

1. totalbytestoreceive: Total number of bytes to be transferred.

2. bytesreceived: number of received bytes.

3. progresspercentage: Percentage of work completed.

 

With the above knowledge, it is very easy to download files using the WebClient component. The following isCodeFramework:

 

 // Download the file with the URL fileaddress from the Web Asynchronously  

Public Void Downloadfilefromweb ( String Fileaddress)

{

WebClient client = New WebClient ();

// Event Response Code after link download is completed

Client. downloadfilecompleted + = client_downloadfilecompleted;

// Response code of the upload progress event

Client. downloadprogresschanged + = client_downloadprogresschanged;

// Start an asynchronous file download task

Uri uri = New Uri (fileaddress );

Client. downloadstringasync (URI );

}

The download completion event response code framework is as follows:

 Void Client_downloadfilecompleted ( Object Sender, asynccompletedeventargs E)

{

If (E. cancelled) // The user canceled the operation.

{

// Process Code ....

}

If (E. Error! = Null ) // An error occurred.

{

// Process Code

}

If (E. userstate! = Null ) // Retrieve task id

{

// Process Code

}

// Other processing code...



}

The download progress event response code framework is as follows:

 
VoidClient_downloadprogresschanged (ObjectSender, downloadprogresschangedeventargs E)

{

StringInfo ="Task ID: {0}, total data: {1} bytes, downloaded: {2} bytes, completed {3} %.";

Info =String. Format (Info, E. userstate, E. totalbytestoreceive, E. bytesreceived, E. progresspercentage );

//.....

}

 

 

Based on the previous content, we can understand EAP as follows:

1. The EAP component defines an asynchronous call method ending with async.

2. When the asynchronous call task ends, a corresponding event is triggered. The event parameters contain important information.

3. The component implementing EAP may provide a method for canceling asynchronous tasks.

4. The EAP component provides an event for reporting progress to users.

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.