TransWikia.com

Stance on safety regarding a delegate based inline thread (and event handling) code using the local variables of the method in which it is declared

Stack Overflow Asked by hecate on November 12, 2021

I am wondering if the use of a local variable of a method is perfectly safe to implement when being used by an inline thread (or event handling) code implemented as a delegate as follows:

// Thread example
class MultithreadExample {
    public MultithreadExample(ref Thread th) {
        int dummyVal;
        
        // Note that dummyVal is used both before and after the start of the thread in this method
        dummyVal = 12;
        
        th = new Thread(new ThreadStart(delegate () {
             // Uses dummyVal is all ways possible!
             dummyVal++;

        }));
        th.Start();
    }
}

// Event handler example
class EventHandlerExample {
    public EventHandlerExample(ref SomeClass obj) {
          int dummyVal;
          
          // Is used all over this method!
          dummyVal = 5;
          obj.SomeEventTriggered += delegate(object sender, SomeEventEventArgs e) {
                // Uses dummyVal extensively!
                dummyVal = 95;
          };
    }
}

As per my tests, I have found out that if, or in any way, a local variable is used this way, the local variable’s existence exceeds beyond the scope of the method and exhibits the behavior of a global class variable, the only caveat being that it can only be accessed by the delegate in concern, but, as stated in the question, am unknown on its safety and the preference of such approach.

Thanks in advance.

One Answer

It doesn't matter what the scope of a variable is when it's accessed from multiple threads. If you're accessing a variable from multiple threads then whether it's a local, instance variable, static variable, or anything else, you need to handle it "properly", whatever "properly" means in your specific case (usually it means synchronizing access to it). There's no "special protection" that a local variable has just because it's a local variable when it comes to multithreaded access.

Answered by Servy on November 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP