c#中如何让一个bool量0.5s为true 0.5s为false 以此循环
时间: 2024-01-22 08:21:28 浏览: 29
你可以使用`System.Timers.Timer`来实现这个功能。首先,你需要定义一个bool变量,然后创建一个Timer对象,并设置它的Interval为500毫秒。在Timer的Elapsed事件中,你可以将bool变量的值在true和false之间切换,并且在每次切换时更新你的应用程序中的状态。
下面是一个示例代码:
```csharp
using System;
using System.Timers;
class Program
{
static bool myBool = false;
static void Main(string[] args)
{
Timer timer = new Timer(500);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
myBool = !myBool;
Console.WriteLine(myBool);
}
}
```
在这个示例中,myBool变量的初始值为false。然后,我们创建了一个Timer对象,并且将它的Elapsed事件处理程序设置为OnTimedEvent函数。在OnTimedEvent函数中,我们将myBool变量的值在true和false之间切换,并且将它的值打印到控制台上。
请注意,Timer的Enabled属性必须设置为true,否则Timer不会开始运行。此外,Timer的AutoReset属性默认为true,这意味着Timer将在每个Interval之后重复触发Elapsed事件。如果你想要仅执行一次,请将AutoReset属性设置为false。