lock keyword in C#

When should the lock be used?

A lock should be used to protect shared resources in multithreaded code. Not for anything else.

But is it necessary when the application does not spin off any other threads?

Absolutely not. It’s just a time waster. However do be sure that you’re not implicitly using system threads. For example if you use asynchronous I/O you may receive callbacks from a random thread, not your original thread.

Is there performance issues with using lock?

Yes. They’re not very big in a single-threaded application, but why make calls you don’t need?

…if that is a good design pattern to follow in the future[?]

Locking everything willy-nilly is a terrible design pattern. If your code is cluttered with random locking and then you do decide to use a background thread for some work, you’re likely to run into deadlocks. Sharing a resource between multiple threads requires careful design, and the more you can isolate the tricky part, the better.

Leave a Comment