我要执行一个在以下条件下每隔特定时间(例如25 ms)接受输入的方法:
I want to execute a method takes inputs every specific time (such as 25 ms) under the following conditions:
提示:我使用了以下代码,但是如果方法延迟> 25 ms,它不会停止执行
Hint: I used the following code but it doesn't stopped the execution if the method delay > 25 ms
private Timer timer1; public void InitTimer() { timer1 = new Timer(); timer1.Tick += new EventHandler(timer1_Tick); timer1.Interval = 1000/40; timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { mymethod() }谢谢
推荐答案我没有机会运行它并检查其100%准确度,但这应该使您了解如何使用Task解决问题:
I didn't get a chance to run this and check its 100% accurate, but this should give you the idea about how to use a Task to solve the problem:
public class Something { public Task _myMethodTask; public CancellationTokenSource _cancelToken; public Timer _myTimer; public Random _rnd; public void Start() { _rnd = new Random((int)DateTime.Now.Ticks); _myTimer = new Timer(TimerElapsedHandler); _myTimer.Change(25, 25); } public void TimerElapsedHandler(object state) { if (!_myMethodTask.IsCompleted) { //The current task is taking too long _cancelToken.Cancel(); } _cancelToken = new CancellationTokenSource(TimeSpan.FromMilliseconds(25)); _myMethodTask = new Task(() => MyMethod(), _cancelToken.Token); } public void MyMethod() { Stopwatch sw = new Stopwatch(); sw.Start(); int delayTimeMs = _rnd.Next(5, 50); while (sw.ElapsedMilliseconds < delayTimeMs) { try { _cancelToken.Token.ThrowIfCancellationRequested(); Thread.Sleep(1); } catch (TaskCanceledException) { return; } } } }正在发生的事情是它使用了每25毫秒运行一次的计时器(在本例中为System.Threading.Timer).它以25毫秒的取消时间开始新任务.任务是MyMethod(),只是为了模拟长时间运行的过程,它会延迟随机时间.您可以添加一些Console.WriteLine或Debug.WriteLine调用以查看其工作情况.
What is happening is that it uses a timer (in this case a System.Threading.Timer) that runs every 25 milliseconds. It starts a new task with a cancellation time of 25 milliseconds. The task is the MyMethod(), and just to simulate a long running process it delays a random time. You can add some Console.WriteLine or Debug.WriteLine calls to see it working.
要注意的重要一点是,您必须定期呼叫_cancelToken.Token.ThrowIfCancellationRequested(); ,而不仅仅是一次.如果请求取消,则该方法将引发异常;如果需要,您可以在退出之前进行清理.如果您不调用它,该任务将不会取消.
The important thing to note is that you have to call _cancelToken.Token.ThrowIfCancellationRequested(); periodically, not just once. The method throws an exception if the cancellation was requested and you can clean up before exiting if need be. If you don't call it, the task will not cancel.
更多推荐
每隔特定时间执行一次方法(毫秒)
发布评论