0

Hi,

I simply if it is an okay practise to use lock objects in functions which is not a background thread.
If we assume that the code that exist in those lock object is no more than just say 5-10 lines of code,
which takes less than 1 milliseconds to execute?

Also we would assume that those lock objects will not be embedded anywhere where deadlocks can occur?

        object lockObject = new object();
        void isnotbackgroundthread1()
        {
            lock (lockObject)
            {
                //5 lines of code
            }
        }
        void isnotbackgroundthread2()
        {
            lock (lockObject)
            {
                //5 lines of code.
            }
        }
2
Contributors
1
Reply
7
Views
4 Years
Discussion Span
Last Post by Ketsuekiame
0

If at any point the code can be executed in the same synchronisation context as another thread (which may be a background thread) then you need to lock. Otherwise, don't bother.

A sychronisation context (not to be confused with the object SyncronizationContext) could be best described as sections of code that can execute in parallel but use the same objects as part of their operation.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.