C#多线程里如何一秒true 一秒false 发送心跳
在C#中,可以使用System.Threading.Timer类来实现定时执行任务。以下是一个示例代码,每隔1秒发送一个心跳,交替为true和false:
using System;
using System.Threading;
class Program
{
private static Timer timer;
static void Main(string[] args)
{
timer = new Timer(SendHeartbeat, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
// 等待程序终止
Console.ReadLine();
}
private static void SendHeartbeat(object state)
{
bool heartbeatValue = DateTime.Now.Second % 2 == 0;
// 发送心跳
Console.WriteLine($"Sending heartbeat: {heartbeatValue}");
// 如果需要在定时器回调方法中修改其他数据,确保使用线程同步机制
lock (timer)
{
// 根据心跳值执行相应操作
if (heartbeatValue)
{
// 执行true时的操作
}
else
{
// 执行false时的操作
}
}
}
}
上述代码中,使用System.Threading.Timer类来创建一个定时器,并在每次定时器回调方法SendHeartbeat中发送心跳。根据当前时间的秒数判断心跳的值为true还是false,并根据需要执行相应的操作。注意,在定时器回调方法内部如果需要修改其他数据,应使用线程同步机制,以避免多线程并发访问的问题
原文地址: https://www.cveoy.top/t/topic/iQCq 著作权归作者所有。请勿转载和采集!