c# - 定时器控制增量计数器

标签 c# timer

所以我尝试在我的代码中添加一个计时器,每 1.5 秒我的 vehCount 就会增加 1。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace AssignmentCA
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Vehicle.vehCount);
            Console.ReadLine();
        }
    class Vehicle
        {
        public static int vehCount = 0;
        private void spawnVehicle()
            {
                Timer tm = new Timer();
                tm.Interval = 1500;
                tm.Elapsed += timerTick;
                vehCount++;
                tm.Start();
            }
            private void timerTick(object sender, EventArgs e)
            {
                vehCount++;
            }
        }
    }
}

在我运行之前和运行时从未使用过计时器,我得到 0,但它从不递增 1。我怎样才能实现这一目标。

最佳答案

我不是很清楚你想做什么,但你根本没有调用 spawnVehicle 方法。

这是针对您发布的内容的解决方案。看 spawnVehicle 是在 Vehicle 类的静态构造函数上调用的!为了从静态构造函数调用 spawnVehicle,它也需要是静态的。

class Vehicle
{
    static Vehicle()
    {
        spawnVehicle();
    }

    public static int vehCount = 0;
    static void spawnVehicle()
    {
        Timer tm = new Timer();
        tm.Interval = 1500;
        tm.Elapsed += (s, e) => vehCount++;
        vehCount++;
        tm.Start();
    }
}

关于c# - 定时器控制增量计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43612527/

相关文章:

c# - 转换印度货币符号

java - java中的定时器任务?

c# - 线程还是非线程

mysql - 类(class)计时器重载服务器

java - 基于网络的多用户倒计时器的设计建议

c# - 8 字节数组返回长(C# 到 C++)

c# - WPF MVVM 在 UI/后台线程之间共享属性

c# - 目录刷新期间遇到错误,未使用新的 dll

c# - 分离 Linq To SQL 和 DTO 的关注点

c# - 计时器在禁用后不想再次启动