Skip to main content

Asynchronous Calls in C# Asp.Net

Asynchronous calls provide a mechanism for increasing the concurrency of your application. Asynchronous calls are nonblocking and when you call a method asynchronously, the calling thread returns immediately and continues execution of the current method.

There are a number of ways to make asynchronous method calls:
  • Calling asynchronous components. Certain classes support the .NET Framework asynchronous invocation model by providing BeginInvoke and EndInvoke methods. If the class expects an explicit call to EndInvoke at the end of the unit of work, then call it. This also helps capture failures if there are any in your asynchronous calls.
  • Calling nonasynchronous components. If a class does not support BeginInvoke and EndInvoke, you can use one of the following approaches:
                    1. Use the .NET thread pool.
                    2. Explicitly create a thread.
                    3. Use delegates.
                    4. Use timers.

Asynchronous Guidelines



This section summarizes guidelines for optimized performance when you are
considering asynchronous execution:
  • Consider client-side asynchronous calls for UI responsiveness.
  • Use asynchronous methods on the server for I/O bound operations.
  • Avoid asynchronous calls that do not add parallelism.

Consider Client-Side Asynchronous Calls for UI Responsiveness


You can use asynchronous calls to increase the responsiveness of client applications. However, think about this carefully because asynchronous calls introduce additional programming complexity and require careful synchronization logic to be added to your graphical interface code.
The following code shows an asynchronous call followed by a loop that polls for the asynchronous call’s completion. You can add an exit criteria to the while condition in case you need to exit from function before call is completed. You can use the callback mechanism or wait for completion if you do not need to update the client.

                IAsyncResult CallResult = SlowCall.BeginInvoke(slow,null,null);
                while ( CallResult.IsCompleted == false)
                {
                    ... // provide user feedback
                }
               SlowCall.EndInvoke(CallResult);

Use Asynchronous Methods on the Server for I/O Bound Operations


You can increase the performance of your application by executing multiple operations at the same time. The two operations are not dependent on each other. For example, the following code calls two Web services. The duration of the code is the sum of both methods.

              // get a reference to the proxy
              EmployeeService employeeProxy = new EmployeeService();
             // execute first and block until complete
              employeeProxy.CalculateFederalTaxes(employee, null, null);
            // execute second and block until complete
            employeeProxy.CalculateStateTaxes(employee);

You can refactor the code as follows to reduce the total duration of the operation. In the following code, both methods execute simultaneously, which reduces the overall duration of the operation. Note that the following example uses the BeginCalculateFederalTaxes method, an asynchronous version of
CalculateFederalTaxes; both of these methods are automatically generated when you reference a Web service from your client application in Visual Studio .NET.

             // get a reference to the proxy
             EmployeeService employeeProxy = new EmployeeService();
             // start async call, BeginCalculateFederalTaxes
             // call returns immediately allowing local execution to continue
             IAsyncResult ar = employeeProxy.BeginCalculateFederalTaxes(employee, null, null);
             // execute CalculateStateTaxes synchronously
             employeeProxy.CalculateStateTaxes(employee);
             // wait for the CalculateFederalTaxes call to finish
             employeeProxy.EndCalculateFederalTaxes(ar);

Avoid Asynchronous Calls That Do Not Add Parallelism


Avoid asynchronous calls that will block multiple threads for the same operation. The following code shows an asynchronous call to a Web service. The calling code blocks while waiting for the Web service call to complete. Notice that the calling code performs no additional work while the asynchronous call is executing.

            // get a proxy to the Web service
            customerService serviceProxy = new customerService ();
            //start async call to CustomerUpdate
            IAsyncResult result = serviceProxy.BeginCustomerUpdate(null,null);
            // Useful work that can be done in parallel should appear here
            // but is absent here
            //wait for the asynchronous operation to complete
           // Client is blocked until call is done
           result.AsyncWaitHandle.WaitOne();
           serviceProxy.EndCustomerUpdate(result);

When code like this is executed in a server application such as an ASP.NET application or Web service, it uses two threads to do one task and offers no benefit; in fact, it delays other requests being processed. This practice should be avoided.

Comments

Popular posts from this blog

Creating package in Oracle Database using Toad For Oracle

What are Packages in Oracle Database A package is  a group   of procedures, functions,  variables   and  SQL statements   created as a single unit. It is used to store together related objects. A package has two parts, Package  Specification  and Package Body.

Resolving 'Setup Account Privileges' error while installing SQL Server

A new installation of Microsoft SQL Server 2012 or Microsoft SQL Server 2008 R2 fails You see the following error message when you try to install a new instance of SQL Server 2012 or SQL Server 2008 R2: Rule "Setup account privileges" failed.

Creating Oracle stored Procedures using TOAD for Oracle

In a database management system, a  stored procedure  is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of  stored procedures  can be helpful in controlling  access to data, preserving  data integrity  and  improving  productivity.