Asynchronous Programming

You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using asynchronous programming. The async and await keywords in C# are intended to help create an asynchronous method (also referred to as async methods) almost as easily as you create a synchronous method. Bridge.NET fully supports async and await and this article demonstrates how to use them to have async methods emitted in your JavaScript code.

Getting Started

Start by creating a new Bridge.NET Class Library project in Visual Studio. If you are not already familiar with this process, please follow the steps described in the Getting Started With Bridge.NET article.

Besides the Bridge and Bridge.Html5 namespaces you also need to install Bridge.jQuery2 which is used by the examples below. Use the NuGet Console and run the following command:

Install-Package Bridge.jQuery

The Bridge\www\demo.html page should also be updated to reference jQuery. Here is what it should look like:

Once the project is set up, you can edit the App.cs file to type in the following examples and run them using the same web page shown above.

Example 1

The first example shows how you can use async methods to improve UI responsiveness. Comparing the synchronous and asynchronous versions of the same code is the best way to see the difference, so there are two classes defined in the code, one for each version. In both cases, the LogData and LongRunningProcess methods do the same work except for the async and await modifiers are used in the asynchronous version. Also, the Task.Delay async method is called to actually initiate concurrency, in the Asynchronous.LongRunningProcess method.

You can click the two buttons repeatedly to see how the web page remains responsive when the async methods are used.

There are two return types for async methods: Task and Task<T>. When converting from synchronous to asynchronous code, any method returning a type T becomes an async method returning Task<T>, and any method returning void becomes an async method returning Task. They are all supported by Bridge.NET.

Example 2

The second example adds two div elements to the web page that start fading in and out when a button is clicked. The async keyword is used with an anonymous delegate to define the button's click event handler.

button.OnClick+=asyncdelegate { };

Animation for each div is supplied as a task to the Task.WhenAll method. This method asynchronously awaits multiple asynchronous operations, which are represented as a collection of tasks and returns a single task that isn’t complete until every task in the collection is completed. The tasks appear to run in parallel, but no additional threads are created. The tasks can complete in any order.