Todays, we have familiar with multi core computer systems. In few years earlier, we were using single processor computer to run the application but then we managed also thread to proper use of processor for increasing the performance of the program. But today, we have huge facilities for writing optimized multithreaded code to use more than one processor separately to boost up the performance dramatically. That’s why; parallel programming model is being more popular day by day.
If we consider for an application in an operating system then the Operating System takes different processes to run for each application/program. Threads are the primary unit which is allocated processor’s time to execute the program. Sometimes, more than one thread is run inside a process or application. The thread maintains a scheduling priority and set of structures that the thread uses to save the thread context and this context contains all required information to complete the task.
In c#, .Net framework provides one single process or thread for any application when a program starts which is called application domain. The app domain can create more thread to process or execute a part of the code. The app domain also can contain more app domain as like threads. So, Threads can manage multiple processors to execute a whole program by dividing multiple units or part of code.
So, when more than one thread is managed to execute a long running program in a parallel way by dividing small part of the code is called multithreading or parallel programming .Net framework provides efficient way to manage all threads by itself using Task based programming. Also in c# 5.0 async and await came with the power of transformation of code to release the blocking of code and resources to optimize the performance inside the current thread.
The .NET Framework provides several ways for application to use multiple threads of execution to keep it responsive while maximizing the performance of your user's computer. Those simple ways are
- Asynchronous Programming Model (APM)
- Event-based Asynchronous Pattern (EAP)
- Task-based Asynchronous Pattern (TAP)
When anybody asks about the multithreading or parallel programming and also asynchronous method writing technique for implementing in their code,I choose very straight forward ways to go with asynchronous programming using one of the recent techniques of c# 5.0 async and wait and Task based asynchronous programming(TAP). Although, we can write asynchronous code using C# earlier but that was more complicated then C# 5.0 version.This tutorial shows you first TAP and then how to use async-await code transformation technique by the compiler. C# 5.0 not only provides the async-await technique but also improved total thread management process for example await sometimes better than Task waiting.
But important things we have to keep in mind that async and await feature does not handover always the current execution point to another thread. It only releases the blocking of code until await point come so that the current execution thread uses free resources to complete other tasks.
So, we can write a full function asynchronously using async and await using almost same pattern of writing synchronous code. Though, the full program is asynchronous but sometimes we need more thread to run few block of code in another thread to make the program multhithreaded. That time we have to use Task based asynchronous programming model. So the combination of both technique makes the code more efficient and optimize the performance for specific scenarios if it is needed.
To start with the model, we have to spend few minutes to re-call the thread, thread pool. Then we will describe the task and task with async-await way to make the code asynchronous with multithreaded.
Threading enables your Visual Basic or C# program to perform concurrent processing so that you can do more than one operation at a time. For example, you can use threading to monitor input from the user, perform background tasks, and handle simultaneous streams of input. For more details go to here.
A thread pool is a collection of threads that can be used to perform several tasks in the background. This leaves the primary thread free to perform other tasks asynchronously.
Thread pools are often employed in server applications. Each incoming request is assigned to a thread from the thread pool, so that the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.
Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.
For more details go to here.
Task uses this thread pool rather than creating a new thread to complete the task. All tasks and thread pool is managed by the system so that the programmer does not worry about multi threading issues. Whereas earlier, we have used a Thread to run another method to execute parallel way, then every time the operating systems creates a new thread without considering the current execution thread is free or not. That’s why, task based asynchronous programming is being more efficient and effective for asynchronous program.
Recently .Net framework providew an object Task which is responsible for asynchronous programming. In System.Threading.Tasks namespace we can find the class. You do not need to worry about the new programming model of Task based programming model. If you have used .NET classic threads, you will see that
standardizing the building blocks for creating and managing tasks can drastically reduce the amount of
code you have to write to create a parallel application..
Task Based Asynchronous Programming
This programming model also known as TAP.The Task-based Asynchronous Pattern (TAP) uses the Task and Task<TResult> types which are used to represent asynchronous operations. Basically it’s a recommendation from Microsoft to write asynchronous APIs in .Net.
Task provides several methods or way for initiation and completion of asynchronous operation. It has differences with APM and EAP model. Because APM uses two different methods those are Start and End program of the operation. On the other hand, EAP dpends on event based programming model. Event-based Asynchronous Pattern (EAP), which requires a method that has the Async suffix and also requires one or more events, handler delegate types and also EventArgs type.
Return type of task is Task or Task<TResult> type.
The programmer must know where asynchronous programming will require or not. For example, it sometimes happen the amount of work required to complete the operation is less than the amount of work required launching the operation asynchronously.
To implement the asynchronous program, the programmer should determine where asynchronous program occurs and also caring about the work load of thread pool.
TaskStatus enumeration represents various status of a Task class because a Task has its own life cycle from initiation to end. A Task maintained by the schedule so whenever a task is created by its public method and not started yet, called it as cold task. When a task starts then it’s known as hot task.
Task cancellation token is used to cancel the task. It is used by both asynchronous method implementers and asynchronous method consumers. The asynchronous operation monitors that any cancellation request comes or not. If come then the process honor it by cancelling the task instantly.
public Task<string> GetProfileInformation(string url)
WebClient webClient = new WebClient();
string info = webClient.DownloadString(url);
Now, we can run the task on various way for various scenario. Immediately we can start the task using
Here, task will run using Thread Pool.If any programmer wants to have more control that which thread does the computation or queue maintenance then he or she can use static proper called Factory of type TaskFactory. The method StartNew of TaskFactory has few overloaded methods those are for use to control of the execution of the program.
Task t = Task.Factory.StartNew(() => MyLongComputation(a, b),cancellationToken,TaskCreationOptions.LongRunning,taskScheduler);
We can generate TAP method on following several ways to use later as an asynchronous method. For example, GetProfileInformation method need to be converted as asynchronous method. So, we can do it simply add Async with it GetProfileInformationAsync. Then we have to add async keyword just before the return type of the signature. We will use the await word where we need to stop the execution part and wait for a return value at the point where the method DownloadString is finished. So, the method looks like,
Public async Task<string> GetProfileInformation(string url)
WebClient webClient = new WebClient();
return await Task.Run(()=> webClient.DownloadString(url));
We can use hybrid method to write a program or convert a program to async.
public Task<int> GetProfileInformationAsync(string url)
if (url== null) throw new ArgumentNullException("url is empty");
private async Task<int> MethodAsyncInternal(string url)
What is async and await
Microsoft’s C# team added a new feature async and await in C# 5. These powerful keywords make life easier to write full program asynchronous.
Async is a great feature of the C# compiler which responsible for code transformation to run your code asynchronously. It simply performs a transformation on your source code of C#.
The feature makes asynchronous programming a lot easier by eliminating the need for
complex patterns that were necessary in previous versions of C#. With it, we can reasonably
write entire programs in an asynchronous style.
I said already that asynchronousprogramming has always been possible in C#, but it involved a lot of manual workfrom the programmer.
Let’s look at synchronous code pattern first then we will convert it to asynchronous function.
Public int UpdateCustomerData(int customerId, string url)
var ProfileHtml = this.GetProfileInformation(url);
CustomerEntities context = new CustomerEntities();
customerInfo.ProfileHtml = ProfileHtml;
Public string GetProfileInformation(string url)
WebClient webClient = new WebClient();
Now call the update function
Now look at the below for equivalent methods using async.
Public async Task<int> UpdateCustomerDataAsync(int customerId,string url)
var ProfileHtml = this.GetProfileInformationAsync(url);
var context = new CustomerEntities();
customerInfo.ProfileHtml = awaitProfileHtml;
return await context.SaveChangesAsync();
private async Task<string> GetProfileInformationAsync(string url)
WebClient webClient = new WebClient();
string info = await webClient.DownloadStringTaskAsync(url);
In first line of UpdateCustomerDataAsync calls the method to get profile page of the customer asynchronously. Then it starts to execute next few lines until it gets the await. When the process get the await then its waiting to finish the task for return value. So, during the fetching of profile information, the program executes to fetch the data of customer object from the database.
The async feature has been designed to find out as similar to blocking code as
possible. We can handle long running program as like synchronously, but keep the performance benefits of calling them asynchronously.
The feature designed to also handle callback operation. You need to be careful with lots of things that behave differently when you use async and await.
While writing asynchronous program or method programmer has to be careful about the following matters,
Exceptions and try..catch...finally blocks
Return values of methods
Threads and context
Though, there is a lot of benefit and advantages of parallel computing using single process or multiple processes. But we have to be careful and should know the applicability of asynchronous program. .Net framework’s asynchronous programming started from the framework 1.0 with IAsyncResult pattern. Framework 2.0 came with event based asynchronous programming model. Now .Net framework 4.5 is has very strong capability to write asynchronous programming rather than thinking a lot. In a single article it’s not possible to touch all the topic of multithreading facilities of C#.