.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Imran Ghani
Sohaib Khalid

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

When to use lock?

Posted By:Jean Paul       Posted Date: February 19, 2011    Points: 75    Category: C#    URL: http://www.dotnetspark.com  

This article When to use lock in your Application using C#. The lock keyword in C# provides good control over a multi-threaded application.

The lock keyword in C# provides good control over a multi-threaded application.
But if we are using it in an unwanted scenario it could impact performance.  Sometimes, the usage of threading itself would not be benefited.
I am trying to explain a valid scenario where lock is advised in a multi-threaded application.

Lock while writing to a file - Advisable

In a multithreaded environment, if a particular method is writing to a file, it is advisable to use lock - otherwise exception will occur.

private void WriteToFile_Locked()
  lock (this)
  StreamWriter streamWriter = File.AppendText("File.txt");
  streamWriter.WriteLine("A line of text..");

Lock while fetching a network resource - Not Advisable

Suppose in a method which is relying on a network resource like copying a file over a network or downloading a file from internet.  In this case the lock would degrade the performance as all the threads will be waiting to enter the critical section.
If we use lock in the above scenario we will not be gaining from the threading advantage.

private void ReadNetworkResource()
  WebClient client = new WebClient();
  var result = client.DownloadData("http://www.google.com");

If we implement lock to the above method it will degrade the performance.

Test Application

A test application is provided to check the performance in both the above scenarios.

The application contains buttons which are self explanatory.  The first row of buttons deals with the file issue and it is solved by implementing the lock keyword.
The second row of buttons deal with the network resource issue where lock is implemented and performance was degraded.  On clicking the buttons we can see the time difference it is taking to perform the actions. 
In the test machine it took 10 seconds for the first one and 25 seconds for the second.
This shows that if lock is not wisely used it could impact the performance in a multi threaded application.
Without Lock With Lock
10 seconds 25 seconds
About the Source
The source for the above application is attached with the article.

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend