我想每10秒钟执行一次C#方法,并且在UtilityClass
类构造函数中使用该方法,但是该方法未执行且没有任何输出。
class Program
{
static void Main(string[] args)
{
UtilityClass utilityClass = new UtilityClass();
}
}
public class UtilityClass : IDisposable
{
private readonly System.Timers.Timer _Timer;
public UtilityClass()
{
_Timer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
_Timer.Elapsed += (sender, eventArgs) =>
{
ExecuteEvery10Sec();
};
}
private void ExecuteEvery10Sec()
{
Console.WriteLine($"Every 10 sec all at {DateTime.Now}");
}
public void Dispose()
{
_Timer.Dispose();
}
}
答案 0 :(得分:1)
有两个问题:一-程序立即终止,因此计时器被销毁。你应该等一下。例如,等待10分钟:
class Program
{
static void Main(string[] args)
{
using (UtilityClass utilityClass = new UtilityClass()) // To dispose after the use
{
System.Threading.Thread.Sleep(10000 * 60); // Waits X milliseconds
}
}
}
您还可以执行无限循环,因此ser只能通过控制台的X按钮(或Ctrl + C)退出。所以:
class Program
{
static void Main(string[] args)
{
using (UtilityClass utilityClass = new UtilityClass()) // To dispose after the use
{
while (true) { }
}
}
}
两个-您应该通过将计时器的Enabled
属性设置为true
来启动计时器:
public class UtilityClass : IDisposable
{
private readonly System.Timers.Timer _Timer;
public UtilityClass()
{
_Timer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
_Timer.Enabled = true;
_Timer.Elapsed += (sender, eventArgs) =>
{
ExecuteEvery10Sec();
};
}
private void ExecuteEvery10Sec()
{
Console.WriteLine($"Every 10 sec all at {DateTime.Now}");
}
public void Dispose()
{
_Timer.Dispose();
}
}