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.
            }
        }

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.