Click here to Skip to main content
15,881,877 members
Articles / Programming Languages / C#
Tip/Trick

Simpler Lock Usage in C#

Rate me:
Please Sign up or sign in to vote.
4.65/5 (9 votes)
10 Dec 2022CPOL 13.9K   11   15
An easier way to use locks in C#
This tip shows how to simplify your lock usage in C#.

I saw a Tweet yesterday complaining about the need to create an empty object to use as the parameter in a lock statement. They wanted this to be simplified.

It struck me that constant strings with the same content all reference the same object as the strings are interned. Thus you could just lock on a constant string without having to create an object. Thus you could do something like the code below. Of course, typos could cause you no end of pain.

Just to be clear, this is not intended to be a 'best practice'. Magic strings and the potential of multiple code sections inadvertently sharing the same string (lock object) far outweigh any benefits this pattern might add. However, it was an interesting observation of one feature of the C# compiler/runtime.

C#
// See https://aka.ms/new-console-template for more information
 
Console.WriteLine($"The strings are the same object {ReferenceEquals("A String", "A String")}");
 
var taskList = new List<Task>();
for (var i = 0; i < 10; i++)
{
    taskList.Add(RunTask1(i));
    taskList.Add(RunTask2(i));
}
 
Task.WaitAll(taskList.ToArray());
 
Console.WriteLine("Done");
 
async Task RunTask1(int i)
{
    await Task.Delay(1);
 
    lock ("A String")
    {
        Console.WriteLine($"Entering task1-{i} lock");
        Thread.Sleep(500);
        Console.WriteLine($"Exiting task1-{i} lock");
    }
}
 
 
async Task RunTask2(int i)
{
    await Task.Delay(200);
    lock ("A String")
    {
        Console.WriteLine($"Entering task2-{i} lock");
        Thread.Sleep(300);
        Console.WriteLine($"Exiting task2-{i} lock");
    }
}
Terminal
The strings are the same object True
Entering task1-0 lock
Exiting task1-0 lock
Entering task1-1 lock
Exiting task1-1 lock
Entering task1-3 lock
Exiting task1-3 lock
Entering task1-2 lock
Exiting task1-2 lock
Entering task1-5 lock
Exiting task1-5 lock
Entering task1-9 lock
Exiting task1-9 lock
Entering task2-7 lock
Exiting task2-7 lock
Entering task2-9 lock
Exiting task2-9 lock
Entering task2-6 lock
Exiting task2-6 lock
Entering task2-5 lock
Exiting task2-5 lock
Entering task2-3 lock
Exiting task2-3 lock
Entering task1-4 lock
Exiting task1-4 lock
Entering task1-8 lock
Exiting task1-8 lock
Entering task1-7 lock
Exiting task1-7 lock
Entering task1-6 lock
Exiting task1-6 lock
Entering task2-8 lock
Exiting task2-8 lock
Entering task2-4 lock
Exiting task2-4 lock
Entering task2-2 lock
Exiting task2-2 lock
Entering task2-1 lock
Exiting task2-1 lock
Entering task2-0 lock
Exiting task2-0 lock
Done   

History

  • 10th December, 2022: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) CodeProject
Canada Canada
As Senior Architect, Matthew is responsible for the Architecture, Design, and Coding of the CodeProject software as well as Manager of the Infrastructure that runs the web site.

Matthew works on improving the performance and experience of the Code Project site for users, clients, and administrators.

Matthew has more years of software development, QA and architecture experience under his belt than he likes to admit. He graduated from the University of Waterloo with a B.Sc. in Electrical Engineering. He started out developing micro-processor based hardware and software including compilers and operating systems.
His current focus is on .NET web development including jQuery, Webforms, MVC, AJAX, and patterns and practices for creating better websites.
He is the author of the Munq IOC, the fastest ASP.NET focused IOC Container.
His non-programming passions include golf, pool, curling, reading and building stuff for the house.

Comments and Discussions

 
QuestionWhy not add a const Pin
tal_segal13-Dec-22 3:34
tal_segal13-Dec-22 3:34 
AnswerRe: Why not add a const Pin
Matthew Dennis13-Dec-22 4:45
sysadminMatthew Dennis13-Dec-22 4:45 
AnswerMagic string anti-pattern Pin
Sergey Alexandrovich Kryukov12-Dec-22 11:39
mvaSergey Alexandrovich Kryukov12-Dec-22 11:39 
GeneralRe: Magic string anti-pattern Pin
Matthew Dennis13-Dec-22 4:46
sysadminMatthew Dennis13-Dec-22 4:46 
QuestionMinus 5 Pin
carloscs12-Dec-22 2:42
carloscs12-Dec-22 2:42 
AnswerRe: Minus 5 Pin
Matthew Dennis12-Dec-22 3:29
sysadminMatthew Dennis12-Dec-22 3:29 
GeneralThoughts PinPopular
PIEBALDconsult11-Dec-22 6:25
mvePIEBALDconsult11-Dec-22 6:25 
GeneralRe: Thoughts Pin
Bruno van Dooren12-Dec-22 2:24
mvaBruno van Dooren12-Dec-22 2:24 
GeneralRe: Thoughts Pin
Matthew Dennis13-Dec-22 5:02
sysadminMatthew Dennis13-Dec-22 5:02 
GeneralRe: Thoughts Pin
PIEBALDconsult13-Dec-22 5:47
mvePIEBALDconsult13-Dec-22 5:47 
GeneralRe: Thoughts Pin
Matthew Dennis13-Dec-22 6:13
sysadminMatthew Dennis13-Dec-22 6:13 
GeneralMy vote of 5 Pin
0x01AA11-Dec-22 4:17
mve0x01AA11-Dec-22 4:17 
QuestionThere's a good reason for using object reference Pin
Mike (Prof. Chuck)10-Dec-22 23:07
professionalMike (Prof. Chuck)10-Dec-22 23:07 
AnswerRe: There's a good reason for using object reference Pin
Matthew Dennis13-Dec-22 5:09
sysadminMatthew Dennis13-Dec-22 5:09 
QuestionNot sure it's simpler Pin
Dmitry Mukalov10-Dec-22 20:20
Dmitry Mukalov10-Dec-22 20:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.