c#如何在课堂上制作周期性事件?

use*_*014 3 c# events multithreading

我想让类每秒更改一个属性.这种变化应该发生在类级而不是主线程中,我该怎么做?

Cas*_*rah 6

您应该使用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.
    }
}
Run Code Online (Sandbox Code Playgroud)

记得在读取属性时锁定实例,因为UpdateProperty是在另一个线程中调用的(ThreadPool线程)