C# – Correct pattern for multi-thread synchronization? (C#)

cmultithreadingsynchronization

I have two threads referencing the same variable — the UI thread and a timer thread. As such, I have wrapped access to it in lock statements in both threads. The timer thread's access has priority — if it's using the variable and the UI thread also wants access, I want the UI thread's operation to complete, but only after the timer thread's operation completes.

However, the timer thread may delegate back to the UI thread, so the UI thread needs to be free to handle that. To accommodate that, I have the UI thread launching a third thread to handle its operation so that it (that third thread) can wait for the timer operation to complete and the UI thread can be available. The locking happens in that third thread.

What is the correct pattern I should be using for this sort of synchronization?

Best Answer

The general recommendation is that whatever is happening in critical sections should be as simple as possible. In particular you should avoid nested locks. Nested locks potentially are the source of deadlocks.

As applied to what you are doing in your 'timer' thread you probably should separate the critical sections from processing. IOW in the timer thread just retrieve the data from the common variable(s) and then do the rest of the processing including interactions with UI thread outside the lock.

Adding a third thread to the mix will not make your life any easier