c# – Will the blocking work correctly?

Question:

I have a lot of locks in my code. I wanted to shorten the code a bit and wrote a small bike. Please tell me if this will work as expected?

public static class LockingCall
{
    public static readonly object LockObject = new object();

    public static void Invoke(Action action)
    {
        lock (LockObject)
        {
            action();
        }
    }

    public static T Invoke<T>(Func<T> function)
    {
        lock (LockObject)
        {
            return function();
        }
    }
}

Answer:

lock only locks those with a shared lock object. Therefore, one should avoid using static or too general objects for this. Locking should be minimal, and therefore the lock object should affect the minimum required number of lock holders (if necessary, use named locks) and lock as little code section as possible.

It is also wrong to lock lock (this), because someone outside can call lock (the object in which lock (this)) and get an unexpected lock.

And of course, if possible, use other methods in the form of thread-safe collections and async / await

Scroll to Top