每隔特定时间执行一次方法(毫秒)

编程入门 行业动态 更新时间:2024-10-28 15:29:50
本文介绍了每隔特定时间执行一次方法(毫秒)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要执行一个在以下条件下每隔特定时间(例如25 ms)接受输入的方法:

I want to execute a method takes inputs every specific time (such as 25 ms) under the following conditions:

  • 每25毫秒运行一次方法.
  • 如果方法延迟大于25 ms,则停止执行并从头开始输入新的输入.
  • 提示:我使用了以下代码,但是如果方法延迟> 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.

    更多推荐

    每隔特定时间执行一次方法(毫秒)

    本文发布于:2023-11-15 00:29:44,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1589516.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:每隔   时间   方法

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!