StackOverflower
StackOverflower

Reputation: 5761

Confusion about System.Timers.Timer

In normal circunstances it should't be possible to access to properties values assigned on main thread on TimerCallback function, right?

I have a class that uses a timer and this class has a method for TimerCallback, well, I access properties on this method as if there were no multithreading (I see the values assigned on main thread)

If necessary I'll paste some code, but I wanted to know first if I have a major confusion in relation to Timers.

Thanks

Upvotes: 1

Views: 190

Answers (3)

scwagner
scwagner

Reputation: 4005

From the documentation for System.Timers.Timer:

If you use the Timer with a user interface element, such as a form or control, without placing the timer on that user interface element, assign the form or control that contains the Timer to the SynchronizingObject property, so that the event is marshaled to the user interface thread.

Upvotes: 2

Cameron
Cameron

Reputation: 98736

You're not supposed to access UI objects except from the thread that created them (usually the main thread). If you do, it might work, but you run the risk of having an exception thrown, or worse, things silently breaking.

Other objects can be accessed by any thread at any time without any exceptions being thrown; however you still have to be careful to avoid concurrency situations. For example, if you have this code to create a singleton:

class Unique {
    private static Unique instance;

    public static Unique Instance {
        get {
            if (instance == null) {
                instance = new Unique();
            }

            return instance;
        }
    }  
}

Then if two threads access the Instance property at the same time, they could both end up creating a new instance of the singleton (since they could both enter the if in parallel).

One of the easiest ways to avoid these scenarios is with locking:

lock (AnyObject) {
    // Any other code locking on the same object cannot run while this code runs
}

Upvotes: 2

Jalal Said
Jalal Said

Reputation: 16162

it should't be possible to access to properties values assigned on main thread on TimerCallback function, right?

Wrong! this is only when you are using UI that rely on the main thread, example when using winforms UI and WPF and even some COM compoents you only should access to its members from the thread that they created on, no matter if it where the main thread or not.

However for a custom class you build, it doesn't matter which thread access the member, that is it, any thread can access the class and its members no matter it it where on the thread that creates that class or not.

Upvotes: 2

Related Questions