Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# how to make periodic events in a 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?

like image 803
user1763014 Avatar asked Feb 19 '23 18:02

user1763014


1 Answers

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)

like image 116
Casperah Avatar answered Feb 27 '23 22:02

Casperah