我有多个对象实例,我试图使用计时器在循环中一个接一个地运行它们。我已经与 chatGPT 交谈了几个小时,但它无法帮助我。
这是我的代码:
public class Program
{
private static OpenSeaApiClient openSeaApiClient;
private static Timer timer;
private static int counter = 1;
static async Task Main()
{
string apiKey = "myApiKey";
openSeaApiClient = new OpenSeaApiClient(apiKey);
// Set up a timer to run every 10 seconds
timer = new Timer(TimeSpan.FromSeconds(10000).TotalMilliseconds);
timer.Elapsed += async (sender, e) => await TimerElapsedAsync();
timer.Start();
Console.WriteLine("Press Enter to exit.");
// Stop the timer when exiting the program
timer.Stop();
timer.Dispose();
}
private static async Task TimerElapsedAsync()
{
Console.WriteLine($"Counter: {counter++}");
var KarafuruXhypebeastXatmos = new Collection(openSeaApiClient, "karafuru-x-hypebeast-x-atmos", "0x32F2a60942E7563CFC42766018641C6C6b10830E", OfferVariables.initialValueOfferKarafuruXhypebeastXatmos);
await KarafuruXhypebeastXatmos.ExecuteAsync();
var BricktopiansByLawDegree = new Collection(openSeaApiClient, "bricktopians-by-law-degree", "0x9eEeAF684E228C2D5C89435e010acC02c41Dc86B", OfferVariables.initialValueOfferBricktopiansByLawDegree);
await BricktopiansByLawDegree.ExecuteAsync();
//more instances
}
当我运行它时,它会转到 Main() 的末尾并停止。它永远不会以 TimerElapsedAsync() 开始。我想要的是 TimerElapsedAsync() 中的进程使用计时器不确定性在循环中一一执行。由于计时器的周期现在设置为 10 秒,我想要发生的事情是在 Main() 方法结束后立即启动 TimerElapsedAsync() 并在执行 TimerElapsedAsync() 中的最后一个进程后等待 10 秒,再次从第一个过程开始。我想我可以使用 while (true) 循环,但这会使用我的记忆,据我所知这不是一个好的解决方案。 请帮我。预先感谢您!
您正在使用
TimeSpan.FromSeconds(10000).TotalMilliseconds
,这意味着您的计时器设置为每 10,000 秒(大约每 166 分钟)触发一次,而不是每 10 秒触发一次。要让计时器每 10 秒触发一次,您应该使用 TimeSpan.FromSeconds(10).TotalMilliseconds
。