gpt4 book ai didi

c# - 如何用 Timer 替换 WHILE

转载 作者:行者123 更新时间:2023-12-02 21:41:15 26 4
gpt4 key购买 nike

我有该代码,我需要用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com