Monday, 22 August 2016

Dispose and Finaliz

Introduction

We have been using the Dispose method for disposing objects in .NET. For the same purpose, we may also use the Finalize method. In this article I will try to explain what the Dispose and the Finalize methods are and where to use the Finalize and where to use the Dispose. I will also try to explain the difference between them.
Dispose
Garbage collector (GC) plays the main and important role in .NET for memory management so programmer can focus on the application functionality. Garbage collector is responsible for releasing the memory (objects) that is not being used by the application. But GC has limitation that, it can reclaim or release only memory which is used by managed resources. There are a couple of resources which GC is not able to release as it doesn't have information that, how to claim memory from those resources like File handlers, window handlers, network sockets, database connections etc. If your application these resources than its programs responsibility to release unmanaged resources. For example, if we open a file in our program and not closed it after processing than that file will not be available for other operation or it is being used by other application than they cannot open or modify that file. For this purpose FileStream class provides Dispose method. We must call this method after file processing finished. Otherwise it will through exception Access Denied or file is being used by other program.

Close Vs Dispose

Some objects expose Close and Dispose two methods. For Stream classes both serve the same purpose. Dispose method calls Close method inside.
void Dispose()
{
     this.Close();
}
Here question comes, why do we need Dispose method in Stream. Having Dispose method will enable you to write below code and implicitly call dispose method and ultimately will call Close method.
using (FileStream file = new FileStream("path", FileMode.Open, FileAccess.Read))
{ 
   //Do something with file 
}
 
But for some classes both methods behave slightly different. For example Connection class. If Close method is called than it will disconnect with database and release all resources being used by the connection object and Open method will reconnect it again with database without reinitializing the connection object. However Dispose method completely release the connection object and cannot be reopen just calling Open method. We will have re-initialize the Connection object.

Creating Dispose

To implement Dispose method for your custom class, you need to implement IDisposable interface. IDisposable interface expose Dispose method where code to release unmanaged resource will be written.

 

Example for implementing the dispose method


1.   public class MyClass : IDisposable
2.   {
3.    private bool disposed = false;
4.    
5.    //Implement IDisposable.
6.    public void Dispose()
7.    {
8.    Dispose(true);
9.    GC.SuppressFinalize(this);
10. }
11. 
12. protected virtual void Dispose(bool disposing)
13. {
14. if (!disposed)
15. {
16. if (disposing)
17. {
18. // TO DO: clean up managed objects
19. }
20. 
21. // TO DO: clean up unmanaged objects
22. 
23. disposed = true;
24. }
25. }
26.}

Finalize

Finalize method also called destructor to the class. Finalize method can not be called explicitly in the code. Only Garbage collector can call the the Finalize when object become inaccessible. Finalize method cannot be implemented directly it can only be implement via declaring destructor. Following class illustrate, how to declare destructor. It is recommend that implement Finalize and Dispose method together if you need to implement Finalize method. After compilation destructor becomes Finalize method.

Example for implementing Finalize method


If you want to implement Finalize method, it is recommended to use Finalize and Dispose method together as shown below:
1.   // Using Dispose and Finalize method together
2.   public class MyClass : IDisposable
3.   {
4.    private bool disposed = false;
5.    
6.    //Implement IDisposable.
7.    public void Dispose()
8.    {
9.    Dispose(true);
10. GC.SuppressFinalize(this);
11. }
12. 
13. protected virtual void Dispose(bool disposing)
14. {
15. if (!disposed)
16. {
17. if (disposing)
18. {
19. // TO DO: clean up managed objects
20. }
21. 
22. // TO DO: clean up unmanaged objects
23. 
24. disposed = true;
25. }
26. }
27. 
28. //At runtime C# destructor is automatically Converted to Finalize method
29. ~MyClass()
30. {
31. Dispose(false);
32. }
33.}

Using Finalize
Now question is, When to implement Finalize? There may be any unmanaged resource for example file stream declared at class level. We may not be knowing what stage or which step should be appropriate to close the file. This object is being use at many places in the application. So in this scenario Finalize can be appropriate location where unmanaged resource can be released. It means, clean the memory acquired by the unmanaged resource as soon as object is inaccessible to application.
Finalize is bit expensive to use. It doesn't clean the memory immediately. When application runs, Garbage collector maintains a separate queue/array when it adds all object which has finalized implemented. Other term GC knows which object has Finalize implemented. When the object is ready to claim memory, Garbage Collector call finalize method for that object and remove from the collection. In this process it just clean the memory that used by unmanaged resource. Memory used by managed resource still in heap as inaccessible reference. That memory release, whenever Garbage Collector run next time. Due to finalize method GC will not clear entire memory associated with object in first attempt.


Tuesday, 15 April 2014

Async and Await Actions in ASP.NET MVC 4



Async Actions in ASP.NET MVC 4

The .NET 4.5 Framework introduced the new async/await asynchronous programming model. With ASP.NET MVC 4 comes the application of the async/await model to controller actions. A traditional ASP.NET MVC control action will be synchronous by nature; this means a thread in the ASP.NET Thread Pool is blocked until the action completes. Calling an asynchronous controller action will not block a thread in the thread pool.
Asynchronous actions are best when your method is I/O, network-bound, or long-running and parallelizable. Another benefit of an asynchronous action is that it can be more easily canceled by the user than a synchronous request. Note that if the controller action is CPU-bound, making the call asynchronous won't provide any benefit.

public async Task<List<Contact>> GetAllAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var context = new ContactContext())
     {
         return await context.Contacts.ToListAsync(cancellationToken);
     }
 }


Compared to the traditional asynchronous approaches the new asynchronous programming model in .NET 4.5 is way cleaner and involves just three main concepts await ,async and Task. The await and async are the keywords introduced in C# 5.0 while Task is a type in the System.Threading.Tasks namespace used for parallel programming. We use task in asynchronous programming to specify the return type of a method. The real beauty of this new approach is that you can write an asynchronous program just as you would write a normal sequential program. async is used to mark a method as being executed asynchronously while await signals that the method is waiting for some processing to complete, like a method call, and cannot continue till that other method completes processing.

So we use this same concept in MVC for requests with high latency. Just for a quick review let’s see how ASP.NET processes a new request. ASP.NET has a pool of threads to service requests, when a new request comes a new thread is picked from the thread pool to service the request. Now this thread that is selected to serve the request cannot serve any other request until the initial request completes. And if this request has a high latency, such as a network operation, then the thread is also blocked until the request finishes execution. So assuming that there are a lot of concurrent high latency calls majority of the threads will be just blocked waiting for the request to finish. So as majority of the threads are just waiting and not doing any processing most of the time, the threads can be better utilized by using asynchronous programming.
In the .NET 4.5 the default maximum size of the thread pool is 5, 000 threads. Though we can extend the size of this thread pool but still the fact is that there is still some limit of the max ThreadPool size and it is always nice not to exhaust this limit of the ThreadPool.
It’s simple to implement asynchronous action methods using the await and async keywords in.NET 4.5.Let’s see how we can implement an action method that makes a network call first using the normal sequential approach and then using the new asynchronous programming approach using the async and await keywords.
The following action method we have implemented returns a List of employees from the database using a service call. Since fetching all the employees may take a considerable amount of time we can implement this action method as an asynchronous method.

In the above method the control does not return back to the calling method until the GetEmployees() web service method completes execution. We can avoid this wait time by implementing the action method asynchronously as below.

If you observe there are only three differences in the asynchronous and synchronous action methods.
  1. In the asynchronous method we are wrapping the return type in a Task while in a normal synchronous method we just return an ActionResult type.
  2. The asynchronous method uses the async keyword in its declaration.
  3. The asynchronous method uses the await keyword while making a method call that is expected to take a while to complete.
If you think that the action method may take to long to execute you can set the timeout using the AsyncTimeout which sets the timeout period in milliseconds. Following method signature sets the timeout of the action method to 200 milliseconds.

[AsyncTimeout(200)]
public async Task<ActionResult> GetEmployeesAsync()
So suppose there is an action method that takes a long time to execute ,implementing the action method asynchronously will not reduce the time much as compared to the synchronous version of the same method. The difference is that the asynchronous approach will just not keep the action method blocked for the time period it is waiting for the call to the external resource like a network call or a database call to complete.
Rather than expecting that implementing the asynchronous action methods will always result in performance improvement it’s always better to evaluate the scenario and the requirement. Implementing asynchronous action methods will bring performance improvement in the following cases:
When there are long running action methods or action methods that are CPU or network intensive.
When you have a multicore system and want to use parallelism to improve the application performance.
So if you have an application that has a lot of concurrent calls that are network or CPU bound using the asynchronous approach will definitely result in performance improvement.



If you have:
public async Task<Query> GetSqlServerData(Query query)
{
    var dt = new DataTable();
    var con = new SqlConnection(query.ConnectionString);

    await con.OpenAsync();
    var cmd = new SqlCommand(query.SelectStatement, con);
    var datareader = await cmd.ExecuteReaderAsync();

    dt.Load(datareader);

    con.Close();
    query.Result = dt;
    return query;
}
Then use:
query1 = await GetSqlServerData(query1);
query2 = await GetSqlServerData(query2);
query3 = await GetSqlServerData(query3);