Search code examples
c#multithreadingeventstimer

How to make periodic events in a C# class?


I want to make a class change one of its properties every second. The change is supposed to happen on class-level and not in the main thread, how would I do this?


Solution

  • You should use System.Threading.Timer:

    private System.Threading.Timer timer;
    
    public YourClass()
    {
        timer = new System.Threading.Timer(UpdateProperty, null, 1000, 1000);
    }
    
    private void UpdateProperty(object state)
    {
        lock(this)
        {
            // Update property here.
        }
    }
    

    Remember to lock the instance while reading the property because the UpdateProperty is called in a different thread (a ThreadPool thread)