The lock keyword in C# provides good control over a multi-threaded
But if we are using it in an unwanted scenario it could impact
performance. Sometimes, the usage of threading itself would not be
I am trying to explain a valid scenario where lock is advised
in a multi-threaded application.
Lock while writing to a file -
In a multithreaded environment, if a particular
method is writing to a file, it is advisable to use lock - otherwise exception
private void WriteToFile_Locked()
StreamWriter streamWriter = File.AppendText("File.txt");
streamWriter.WriteLine("A line of text..");
Lock while fetching a network resource -
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");
implement lock to the above method it will degrade the
A test application is
provided to check the performance in both the above scenarios.
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
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.
the test machine it took 10 seconds for the first one and 25 seconds for the
This shows that if lock is not wisely used it could impact the
performance in a multi threaded application.
The source for the above application is attached with the