我想让一个类每秒改变它的一个属性。更改应该发生在类级别,而不是在主线程中,我该如何做呢?
发布于 2012-10-21 20:12:25
您应该使用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.
}
}请记住在读取属性时锁定实例,因为UpdateProperty是在另一个线程( ThreadPool线程)中调用的
发布于 2012-10-21 20:13:31
如果你想在不同的线程上运行,可以使用BackgroundWorker,并将更改属性的逻辑放在DoWork中。
如果你想重复做一些事情,你应该在backgroundworker的DoWork()方法中使用loop,而不是使用Timer类,因为和BackgroundWorker一起使用似乎没有意义。下面是一些粗略的代码:
public Form1()
{
InitializeComponent();
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(DoWork);
}
private void DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
int delay = 1000; // 1 second
while (!worker.CancellationPending)
{
do something
Thread.Sleep(delay);
}
e.Cancel = true;
}每当您想要停止属性更新时,都会像这样调用worker实例上的CancelAsync -
worker.CancelAsync();发布于 2021-11-04 18:57:31
现在在.net 6中这很简单。
using System;
using System. Threading;
using PeriodicTimer timer = new (TimeSpan.FromSeconds (1));|
while (await timer.WaitForNextTickAsync ())
{
//implement your code here
}https://stackoverflow.com/questions/12997658
复制相似问题