我有以下方法
public static class PublisherClass {
public static async Task PublishToMethod(string methodName, string message) {
switch (methodName) {
case "start":
PayloadCreator.SetTimer(timeInterval);
}
}
}
public static class PayloadCreator {
public static void SetTimer(int timeInterval) {
aTimer = new System.Timers.Timer(timeInterval);
aTimer.Elapsed += SendPeriodic;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
public static async void SendPeriodic(Object source, ElapsedEventArgs e) {
Console.WriteLine("Starting to send periodic Telemetry at {0:HH:mm:ss.fff}", e.SignalTime);
await SendPeriodicTimeSeries(PublisherClass.TimeSeriesTopic, PublisherClass.TelemetrySingle, PublisherClass.Configuration);
await SendPeriodicAlarm(PublisherClass.AlarmTopic, PublisherClass.AlarmSingle);
}
}
每当调用“ PublishToMethod”时,Timer就会启动,并会定期发送某些内容的定期调用。我觉得Timer代码不是完全异步的。如果我两次调用,它的行为就会有所不同。定期时间间隔中断。
我需要运行多次调用Timer的异步调用的Timer方法。我该如何实现?
The problem you have here is not one of asynchrony, it is the fact that your
PayloadCreator
is a static class, and given the method signatures, your timer is also static.Static items are instantiated once in the lifetime of your app domain - in this case, every time you call
SetTimer
, you are changing the properties of the timer used by all the other previous calls toPublishToMethod
.我不确定您的要求,因此无法告诉您如何进行重组,但是如果计时器在不同的“已发布”项目中需要不同,那么您将无法保持此静态结构。