作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有该代码,我需要用 Timer 替换 WHILE 来定期工作。
可能吗?
private CancellationTokenSource ts = new CancellationTokenSource();
public void Start()
{
CancellationToken ct = ts.Token;
Task.Factory.StartNew(() =>
{
while (true)
{
// do some heavy work here
Thread.Sleep(200);
if (ct.IsCancellationRequested)
{
// another thread decided to cancel
Debug.WriteLine("task canceled");
break;
}
}
}, ct);
// Simulate waiting 3s for the task to complete
// Thread.Sleep(3000);
}
public void Stop()
{
// Can't wait anymore => cancel this task
ts.Cancel();
}
最佳答案
我相信以下应该可以解决问题:
private CancellationTokenSource ts = new CancellationTokenSource();
public void Start()
{
System.Timers.Timer t = new System.Timers.Timer();
t.Interval = 200;
t.Elapsed += (s, e) =>
{
if (ts.Token.IsCancellationRequested)
{
// another thread decided to cancel
Debug.WriteLine("task canceled");
t.Stop();
}
}
t.Start();
}
public void Stop()
{
// Can't wait anymore => cancel this task
ts.Cancel();
}
您不再需要线程,因为计时器已经位于单独的线程上。
关于c# - 如何用 Timer 替换 WHILE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405897/
我是一名优秀的程序员,十分优秀!