在任务中每秒运行一次方法

问题描述 投票:-2回答:1

我创建了这样的方法:

public static void StartCalculate()
    {
        Task.Run(async () =>
        {
            while (true)
            {
                calculatePosition.Pass();
                await Task.Delay(1000);
            }
        });
    }

我不知道如何,它有时会在1秒内启动2次此方法。我从其他地方添加元素到列表中。方法传递此列表上的calculate元素并将其删除。每秒一秒,它应该为列表中的每个元素计算一次。但有时它会共享清单2。此方法在200秒时计算了260次。当List.Count = 0时,我没有启动此方法。当我没有阻止此方法时,此启动频率更高。

c# task
1个回答
0
投票

创建计时器:

System.Timers.Timer intervalTime = new System.Timers.Timer();
intervalTime.Elapsed += new ElapsedEventHandler(calculatePosition.Pass());
intervalTime.Interval = 1000;
intervalTime.Enabled = true;
intervalTime.Start();
© www.soinside.com 2019 - 2024. All rights reserved.