gpt4 book ai didi

c# - 用定时器替换代码而不是线程 sleep

转载 作者:太空宇宙 更新时间:2023-11-03 23:42:59 25 4
gpt4 key购买 nike

根据这个Stack Overflow discussion ,使用 Thread.Sleep() 几乎总是一个坏主意。我将如何重构我的代码以改用计时器。我试图通过执行以下操作开始:

namespace Engine
{
internal class Program
{
public static DbConnect DbObject = new DbConnect();

System.Timers.Timer timer = new System.Timers.Timer();

// error here
timer.Interval = 2000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled=false;
}
}

但不断收到 cannot resolve symbol 错误消息。

namespace Engine
{
internal class Program
{
public static DbConnect DbObject = new DbConnect();
private static void Main()
{
SettingsComponent.LoadSettings();

while (true)
{
try
{
for (int x = 0; x < 4; x++)
{
GenerateRandomBooking();
}
Thread.Sleep(2000);
GenerateRandomBids();
AllocateBids();
Thread.Sleep(2000);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}

最佳答案

如果您使用的是 .Net 4.5 或更高版本,则可以使用 await 而不是 Timer。

例如:

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

namespace Demo
{
public static class Program
{
private static void Main()
{
Console.WriteLine("Generating bids for 30 seconds...");

using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
{
var task = GenerateBids(cancellationTokenSource.Token);

// You can do other work here as required.

task.Wait();
}

Console.WriteLine("\nTask finished.");
}

private static async Task GenerateBids(CancellationToken cancel)
{
while (!cancel.IsCancellationRequested)
{
Console.WriteLine("");

try
{
for (int x = 0; x < 4; x++)
GenerateRandomBooking();

await Task.Delay(2000);

if (cancel.IsCancellationRequested)
return;

GenerateRandomBids();
AllocateBids();

await Task.Delay(2000);
}

catch (Exception e)
{
Console.WriteLine(e);
}
}
}

private static void AllocateBids()
{
Console.WriteLine("AllocateBids()");
}

private static void GenerateRandomBids()
{
Console.WriteLine("GenerateRandomBids()");
}

private static void GenerateRandomBooking()
{
Console.WriteLine("GenerateRandomBooking()");
}
}
}

关于c# - 用定时器替换代码而不是线程 sleep ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28429300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com