如何让c#方法在计时器上运行?

问题描述 投票:0回答:2

如何在计时器上运行C#方法?我在网上找到了这个例子,但下面的DoStuffOnTimer()方法没有被点击:

    public void DoStuff()
    {
        var intervalMs = 5000;
        var timer = new Timer(intervalMs);
        timer.Elapsed += new ElapsedEventHandler(DoStuffOnTimer);
        timer.Enabled = true;
    }

    private void DoStuffOnTimer(object source, ElapsedEventArgs e)
    {
        //do stuff
    }
c# .net
2个回答
1
投票

或者,如果您不需要非常精确的计时器,您可以自己创建它:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace Temp
{
    internal class Program
    {
        // this is the `Timer`
        private static async Task CallWithInterval(Action action, TimeSpan interval, CancellationToken token)
        {
            while (true)
            {
                await Task.Delay(interval, token);
                if (token.IsCancellationRequested)
                {
                    return;
                }

                action();
            }
        }

        // your method which is called with some interval
        private static void DoSomething()
        {
            Console.WriteLine("ding!");
        }

        // usage sample
        private static void Main()
        {
            // we need it to add the ability to stop timer on demand at any time
            var cts = new CancellationTokenSource();

            // start Timer
            var task = CallWithInterval(DoSomething, TimeSpan.FromSeconds(1), cts.Token);

            // continue doing another things - I stubbed it with Sleep
            Thread.Sleep(5000);

            // if you need to stop timer, let's try it!
            cts.Cancel();

            // check out, it really stopped!
            Thread.Sleep(2000);
        }
    }
}

0
投票
using System;
using System.Timers;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            Program thisone = new Program();
            thisone.DoStuff();
            Console.Read();
        }

        public void DoStuff()
        {
            var intervalMs = 5000;
            Timer timer = new Timer(intervalMs);
            timer.Elapsed += new ElapsedEventHandler(DoStuffOnTimer);
            timer.Enabled = true;
        }

        private void DoStuffOnTimer(object source, ElapsedEventArgs e)
        {
            //do stuff
            Console.WriteLine("Tick!");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.