开发者

Confusion about System.Timers.Timer

开发者 https://www.devze.com 2023-03-25 15:02 出处:网络
In normal circunstances it should\'t be possible to access to properties values assigned on main thread on TimerCallback function, right?

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


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.


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
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消