Use .NET asynchronous programming (1)

zhaozj2021-02-17  26

Use the .NET asynchronous programming, call the .NET class method while the program continues to perform, until the specified callback is performed; or if the callback is not provided, the call or waits is completed until the calling block, polling or waits. For example, a program can call a method that enumerates a larger list while the main program will continue. After completing the enumeration, callback and the program is addressed.

Asynchronous programming is a function supported by the .NET framework, these areas include:

Document IO, stream IO, socket IO

Network: http, TCP

Remote processing channel (HTTP, TCP) and proxy

XML Web Services created using ASP.NET

ASP.NET web form

MSMQ on message processing message queue

Asynchronously commission

Asynchronous programming overview

One of the following four methods can be used. Net asynchronous calls:

Use the callback to provide a callback delegation when starting asynchronous calls.

The polling is completed for the call to complete the IASYNCRESULT.IsCompleted property that the polling has returned.

Start calling, ending the call attempts to complete the operation too early, thus blocking before the operation is completed.

Start call, wait for processing, and end call waiting for IASYNCRESULT. This option is the difference between the previous options that the client can wake up periodically.

Through the .NET asynchronous programming, the server splits asynchronous operation into two logical parts: the part of the input from the client and starts an asynchronous operation, providing the part of the result of the asynchronous operation. Further, the input required for asynchronous operations, the first portion also adopts the AsyncCallBack that will be called after the asynchronous operation is completed. The first part returns a waiting object that implements the IASYNCRESULT interface used by the client to determine the state of asynchronous operation. The server typically uses the first portion to return to the client's waiting object to maintain any state associated with the asynchronous operation. By providing the waiting object, the client uses the second part to get the result of the asynchronous operation.

cancel

Cancel is not available on the IASYNCRESULT interface. Cancel is not available on IasyncResult, because in many implementations, there may be no guarantees for canceling the Beginxxx call. The disclosure and implementation of the cancellation of asynchronous Beginxxx is performed by the intent of the class in its disclosure Beginxxx and Endxxx. You can also choose to provide the Cancelxxx method.

abnormal

Beginxxx. If the Beginxxx method triggers an exception, the caller can assume that the asynchronous operation does not start, and the callback delegation will not be adjusted. Beginxxx can initiate structural exceptions.

Endxxx. Returns an exception from an asynchronous operation by triggeting an exception from an ENDXXX method. Endxxx can initiate an abnormality of the structure and the called object.

Asynchronous programming design mode

The asynchronous mode is the core technology in the .NET framework. It provides a valid model to manage asynchronous operations and consistent programming models. After you know how to use asynchronous mode with the IO class, you can easily use the asynchronous mode with the network class, commission, etc. (including the new API).

Asynchronous design pattern overview

One of the innovations provided by asynchronous modes is that the caller determines whether a particular call should be asynchronous. For object called, there is no need to perform additional programming to support asynchronous behavior of its client; this function is provided in this mode. The difference between the public language runtime processing caller and the object being called. The object being called can select explicitly support asynchronous behavior, this or because it can effectively achieve asynchronous behavior than the general structure, or because it wants to support the asynchronous behavior of its caller. However, it is recommended that this called object follows the asynchronous design pattern of public asynchronous operations.

Type security is another innovative in asynchronous mode. Especially for asynchronous delegation, language compilers for .NET framework and public language logo can make the start and end operations that map to the rule invoke method (for example, beginInvoke, and endinvoke) are safe. This is very important because the compiler is subjected to the asynchronous commission to split into the start and end operation, so that it can only pass the valid parameters. The basic idea contained in this mode is as follows:

The caller determines whether a particular call should be asynchronous.

For objects called, there is no need to perform additional programming from its client to support asynchronous behavior. The public language runtime structure should be able to process the difference between the caller and the called object view.

The object being called can select explicitly support asynchronous behavior, this or because it can effectively achieve asynchronous behavior than the general structure, or because it wants to support the asynchronous behavior of its caller. However, it is recommended that this called object follows the asynchronous design pattern of public asynchronous operations.

The compiler is the Signature of BeginInvoke and EndInvoke and asynchronously entrustment.

The .NET framework provides services needed to support asynchronous programming models. Some columns represent examples of such services are:

Synchronous primitives, such as monitors, and reader writers locked.

Threads and thread pools.

Synchronous configuration, such as a container that supports waiting objects.

Open to the base structure (such as iMessage object and thread pool).

This mode splits a synchronous call into each component: Start operation, ending operations, and results objects. Considering the following examples, in which the Factorize method may be done in a large amount of time.

Public Class PrimeFactorizer

{

Public Bool Factorize (Int Factorizables, Ref Int PrimeFactor1, Ref Int PrimeFactor2)

{

// determine WHether FactorizAblenum is prime.

// if is prime, return true. OtherWise, Return False.

// IF is prime, Place Factors in PrimeFactor1 and primefactor2.

}

}

If you follow the asynchronous mode, the class library write writer adds the BegInFactorize and EndFactorize methods, and the two methods are split into two asynchronous operations:

Public Class PrimeFactorizer

{

Public Bool Factorize

Int FactorizAblenum,

Ref int primefactor1,

Ref Int PrimeFactor2)

{

// determine WHether FactorizAblenum is prime.

// if is prime, return true; OtherWise Return False.

// if is prime paractors in primefactor1 and primefactor2

}

Public IASYNCRESULT BEGINFAACTORIZE

Int FactorizAblenum,

Ref int primefactor1,

Ref int primefactor2,

AsyncCallback Callback,

Object State)

{

// begin the factory inynchronously, and return a result Object,

}

Public Bool EndFactorize

Ref int primefactor1,

Ref int primefactor2,

IASYNCRESULT AsyncResult

)

{

// end (or completion) The facts, and // return the results,

// and Obtain the prime factors.

}

}

The server splits asynchronous operation into two logical parts: the part of the input from the client and calls the asynchronous operation, providing the part of the asynchronous operation result to the client.

In addition to the input required for asynchronous operation, the first portion also adopts the AsyncCallback delegation to be called after completing asynchronous operation. The first part returns a waiting object that implements the IASYNCRESULT interface used by the client to determine the state of the asynchronous operation.

The server also uses it returns to the client's waiting object to maintain any status associated with the asynchronous operation. By providing the waiting object, the client uses the second part to get the result of the asynchronous operation.

Options that can be used for the client to start asynchronous operations:

The callback delegation is provided when starting asynchronous calls.

Public Class Driver1

{

Public PrimeFactorizer PrimeFactorizer;

Public void Results (IasyncResult asyncResult)

{

INT PrimeFactor1 = 0;

INT PrimeFactor2 = 0;

Bool prime = primefactorizer.endfactorize

Ref princimefactor1,

Ref princimefactor2,

AsyncResult);

}

Public void Work ()

{

INT factorizables = 1000589023,

INT PrimeFactor1 = 0;

INT PrimeFactor2 = 0;

Object State = new object ();

PrimeFactorizer = new primefactorizer ();

AsyncCallback Callback = New Callback (this.Results);

IASYNCRESULT AsyncResult = primefactorizer.beginfactorize

FactorizAblenum,

Ref princimefactor1,

Ref princimefactor2,

Callback,

State);

}

}

The callback delegation is not available when starting asynchronous calls.

Public Class Driver2

{

Public Static void Work ()

{

INT factorizables = 1000589023,

INT PrimeFactor1 = 0;

INT PrimeFactor2 = 0;

Object State = new object ();

PrimeFactorizer PrimeFactorizer = New PrimeFactorizer ();

AsyncCallback Callback = New Callback (this.Results);

IASYNCRESULT AsyncResult = primefactorizer.beginfactorize

FactorizAblenum,

Ref princimefactor1,

Ref princimefactor2,

Callback,

State);

Bool prime = primefactorizer.endfactorize

Ref princimefactor1,

Ref princimefactor2,

AsyncResult);

}

}

Asynchronous method signature

The method signature is the order in which the parameter type is in one method. BEGININVOKE is the rules for asynchronous method:

Includes all IN parameters.

Includes all OUT parameters.

Includes all IN / OUT parameters.

Includes all byref parameters. Get AsyncCallback and AsyncState (available through the asyncState property on the IASYNCRESULT interface) as the last two parameters.

Return to IASYNCRESULT.

EndInvoke asynchronous method Signature rules are:

Includes all IN / OUT parameters.

Includes all OUT parameters.

Includes all byref parameters.

The IASYNCRESULT as the last parameter.

Returns the original return type from the original method signature.

The result object (IASYNCRESULT) is returned from the start operation and can be used to obtain a status of whether or not the asynchronous start operation has been completed. The result object is passed to the end operation, which returns the final return value of the call. An optional callback can be provided in the start operation. If the callback is provided, the callback will be called after the call is completed; and the code in the callback can call the end operation.

IASYNCRESULT interface

The IASYNCRESULT interface is used to monitor and manage asynchronous operations. The interface is to be returned from the start operation to the end operation to associate the start operation and end operation. If the callback is specified as part of the start operation, the AsyncResult is passed to the callback. The following code explains the properties of the IASYNCRESULT interface that can be used to monitor the status of asynchronous operations and get an asynchronous state object that can also be passed to the start operation:

Public Interface IasyncResult

{

Object asyncState {get;}

Waithandle asyncwaithandle {get;}

Bool completedsynchronously {get;}

Bool iscompleted {get;}

}

AsyncState returns an object that is provided as the last parameter (as part of the start operation method call).

AsyncWaitHandleAsyncWaitHandle Attributes Returns WaitHandle, which can be used to perform WaitHandle.Waitone, Waitany or Waitall.

CompletedSynchronously If the start operation call is completed synchronously, the completedsynchronously property will be set to "True".

ISCompleted After the server completes the call processing, the iScompleted property will be set to "True".

AsyncCallback commission used for asynchronous operation

The AsyncCallback commissioned for specifying the method that should be called after the start operation is completed. As shown in the following code, the AsyncCallback commissioned as the second to the last parameter on the start operation:

Public Delegate Void AsyncCallback (IASYNCRESULT AR);

转载请注明原文地址:https://www.9cbs.com/read-28550.html

New Post(0)