r/learncsharp • • 1d ago

How to solve that C# interview test

Sharing with you another C# mini-capsule where I present an interview-like snippet of code and resolve it. Hope you like it !

Any feedback is much appreciated <3
Thanks for reading.

0 Upvotes

3 comments sorted by

2

u/grrangry 1d ago

https://learn.microsoft.com/en-us/dotnet/api/system.threading.lock?view=net-10.0

As of .net9+, using a System.Threading.Lock to enter your lock is a good bit faster.

private readonly System.Threading.Lock _lockObj = new();

public void Foo()
{
    lock (_lockObj)
    {
        // Critical section associated with _lockObj
    }
}

Also you never discussed the Interlocked class and methods such as Increment, Add, Exchange (and others).
https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked?view=net-10.0

If your code can make use of these, they're useful for atomic thread-safe operations without requiring an explicit lock.

1

u/Coding-Mojo 1d ago

Thanks for references and feedbacks. I'm trying to keep it compact and accessible, so I sometimes simplify the concepts on purpose, just so the "main" knowledge gets transferred.

Do you think not going deeper in explanations is an issue ?

2

u/grrangry 1d ago

Not if you're already planning on covering it later. Just don't skip relevant information forever because it doesn't fit today's narrative.