如何在 .NET Core 中打勾?时间跨度?自动收报机?
How to tick in .NET Core? Timespan? Ticker?
我习惯了 timers/ticking 的旧 WCF 方式。例如,我希望每 25 秒调用一次某个方法。我如何在 .NET Core 中执行此操作?
您可以使用 System.Threading.Timer。请注意,此 Timer 不是线程安全的 - 有关详细信息,请参阅此问题:Timer (System.Threading) thread safety
.
namespace TimerApp
{
public class Program
{
public static void Main(string[] args)
{
using (new System.Threading.Timer(DoSomething, null , 0, 250))
{
// do something else
Thread.Sleep(TimeSpan.FromDays(1));
}
}
public static void DoSomething(object state)
{
// called every 250ms
Console.WriteLine(DateTime.Now);
}
}
}
我习惯了 timers/ticking 的旧 WCF 方式。例如,我希望每 25 秒调用一次某个方法。我如何在 .NET Core 中执行此操作?
您可以使用 System.Threading.Timer。请注意,此 Timer 不是线程安全的 - 有关详细信息,请参阅此问题:Timer (System.Threading) thread safety .
namespace TimerApp
{
public class Program
{
public static void Main(string[] args)
{
using (new System.Threading.Timer(DoSomething, null , 0, 250))
{
// do something else
Thread.Sleep(TimeSpan.FromDays(1));
}
}
public static void DoSomething(object state)
{
// called every 250ms
Console.WriteLine(DateTime.Now);
}
}
}