Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing lock statement within a loop in C#
    primarykey
    data
    text
    <p>Lets take the sample class SomeThread where we are attempting to prevent the DoSomething methods from being called after the Running property is set to false and Dispose is called by the OtherThread class because if they are called after the Dispose method is the world would end as we know it.</p> <p>It feels like there is a chance for something evil to happen because of the loop. That at the point where it starts the next loop and before the lock is taken before calling the DoSomething methods, Running could be changed to false, and Disposed called before it hits the lock. In this scenario life would not be good. </p> <p>I was looking at ways to handle this when using a loop in a simple easy to maintain method. For the record I did considered the Double Lock Check patterned, however it is does not seem to be recommend for C#. </p> <p><strong><em>Warning:</strong> This is a simplified example to try to make it easy to focus on the issue with the loop and locking within one. If I didn't elaborate enough some place please let me know and I will do my best to fill in any details.</em> </p> <pre><code>public class SomeThread : IDisposable { private object locker = new object(); private bool running = false; public bool Running { get { lock(locker) { return running; } } set { lock(locker) { running = value; } } } public void Run() { while (Running) { lock(locker) { DoSomething1(); DoSomething2(); } } } private void DoSomething1() { // something awesome happens here } private void DoSomething2() { // something more awesome happens here } public void Dispose() { lock (locker) { Dispose1(); Dispose2(); } } private void Dispose1() { // something awesome happens here } private void Dispose2() { // something more awesome happens here } } public class OtherThread { SomeThread st = new SomeThread(); public void OnQuit() { st.Running = false; st.Dispose(); Exit(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload