简体   繁体   English

如何使用Timer.Timer(或)如何将循环中的一些代码从当前定时器循环到给定时间?

[英]how to loop through piece of code from current timer to given time using Timer.Timer (or) How to add Timer to loop?

I have to loop through code for specified time .I achieved it with DateTime 我必须循环遍历代码指定的时间。我用DateTime实现了它

var time=DateTime.Now.AddMinutes((Convert.ToDouble(1)));
while(DateTime.Compare(DateTime.Now, time) <= 0)
{
  console.write("some message..")
}

How do i achieve the same with Timer.Timer or thread.timer which is best approach.. 我如何使用Timer.Timer或thread.timer实现相同的方法,这是最好的方法..

Is it possible to write 10 times per sec? 是否有可能每秒写10次? Can anyone suggest. 谁能建议。 thank you 谢谢

    static void Main(string[] args)
    {
        System.Threading.Timer timer = null;
        int counts = 0;
        timer = new Timer((obj) =>
        {
            Console.WriteLine(counts);
            if (++counts > 10)
                timer.Dispose();

        }, null, 100, 100);


        for (;;) ;
    }

will call the method dosomething() after 100ms, every 100ms in the background, till timer.Dispose() is called; 将在100ms后调用dosomething()方法,在后台每100ms调用一次,直到调用timer.Dispose(); this implementation will ofc never terminate as it is written here ;) 这个实现将永远不会终止,因为它写在这里;)

在此输入图像描述

if you are going to make this work you need to make your program multithreaded , 如果你要完成这项工作,你需要让你的程序多线程

See System.Threading and System.Threading.Task 请参见System.ThreadingSystem.Threading.Task

Once you have your code executing in it's own thread, (using Thread, Task, Timer or any of the other variations in those namespaces) you can tell it to stop executing for a set amount of time, this is done by calling the Thread.Sleep or Task.Delay methods. 一旦你的代码在它自己的线程中执行,(使用Thread,Task,Timer或这些命名空间中的任何其他变体),你可以告诉它在一段时间内停止执行,这是通过调用Thread来完成的。 Sleep或Task.Delay方法。

eg 例如

Task.Run(()=>
{
    do
    {
        //do something
        await Task.Delay(100);
    }
    while(! exitCondition)
});

however you shouldn't count on this for exact timing as what you are doing is saying to the OS that this thread doesn't need to be executed for that amount of time, it doesn't mean the OS will pass it to the processor immediately on the time running out. 但是你不应该指望这个准确的时间,因为你正在做的是告诉操作系统这个线程不需要执行那段时间,这并不意味着操作系统会将它传递给处理器马上就耗尽了。 depending on how busy the CPU is there can be quite a delay before your thread reaches the top of the waiting to process queue. 取决于CPU的繁忙程度,在线程到达等待处理队列的顶部之前可能会有相当长的延迟。 if the timing is vitally important then i would set a lower time and check the clock before running 如果时间非常重要,那么我会设置较短的时间并在跑步前检查时钟

You could always use StopWatch , which is accurate and most appropriate for your scenario. 您始终可以使用StopWatch ,它准确且最适合您的方案。

Action<long> action = (milliseconds) =>
{
    Console.WriteLine("Running for {0}ms", milliseconds);

    Stopwatch watch = new Stopwatch();
    watch.Start();

    while (watch.Elapsed.TotalMilliseconds <= milliseconds)
    {
        Console.WriteLine("ticks:{0}", DateTime.Now.Ticks);
        Thread.Sleep(100);
    }

    Console.WriteLine("Done");
    watch.Stop();
};

Task.Run(() => action(1000));

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM