In this post, I am going to run through a simple example using Asp.net MVC. We are going to build a page that performs a long running task on the server using Web Workers. First off, create a new MVC project in Visual Studio.
Then add a new Controller, and let's add a new method on the Controller - I called mine "Webworkers".
This is just going to be a simple page that calls a long running process on our Controller using HTML5 Web Workers. Add the following code to your View.
The above code is using XMLHttpRequest object to do a simple POST request to a method on our Controller. Let's create the method on the Controller and call it "UpdateStats". In this example, I am not passing any parameters through, but these could just as easily be added onto the request. Workers use a method called "postMessage" to return a result to the thread that called it. Whatever we return in this postMessage will be returned to the original thread.
As you will have noticed, I included a reference to Modernizer to check if the browser supports Workers. At the time of writing this article, there is a surprising amount of support for Web Workers. However, some of the major browsers (IE) are still playing a bit of catch-up. Firefox, Chrome, Safari, Opera and IE (10) all offer support for Workers. For more information check out caniuse.com. If the browser that you are targeting doesn't fully support Web Workers yet, you could simply fall back to calling the service traditionally.
For more information on the HTML5 Web Workers spec, please check out the W3C draft. There are some good simple examples on using Workers on the site. A copy of the project used in this example is available to download here.