是的,计时器是一个很好的方法。
我有一个类似的 Blazor 组件,称为 Sprite,每次计时器事件发生时我都会在其中执行图像的移动。
在我的例子中,我的订阅者是一个接口,ISpriteSubscriber:
namespace DataJuggler.Blazor.Components.Interfaces
{
#region interface ISpriteSubscriber
/// <summary>
/// This interface is used by the AnimationManager to notifiy callers that a refresh occurred.
/// </summary>
public interface ISpriteSubscriber
{
#region Methods
#region Refresh()
/// <summary>
/// This method will call StateHasChanged to refresh the UI
/// </summary>
void Refresh();
#endregion
#region Register(Sprite sprite)
/// <summary>
/// This method is called by the Sprite to a subscriber so it can register with the subscriber, and
/// receiver events after that.
/// </summary>
void Register(Sprite sprite);
#endregion
#endregion
#region Properties
#region ProgressBar
/// <summary>
/// This is used so the ProgressBar is stored and available to the Subscriber after Registering
/// </summary>
ProgressBar ProgressBar { get; set; }
#endregion
#endregion
}
#endregion
}
public ISpriteSubscriber Subscriber { get; set; }
在我的开始事件中,我创建了计时器:
public void Start()
{
this.Timer = new Timer();
this.Timer.Interval = this.interval;
this.Timer.Elapsed += Timer_Elapsed;
this.Timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
// if a subscriber (returns true if Subscriber != null)
if (HasSubscriber)
{
// Notify Subscriber
Subscriber.Refresh();
}
}
public void Refresh()
{
// do your actions here
}
public void Register(Sprite sprite)
{
// If the sprite object exists
if (NullHelper.Exists(sprite))
{
// if this is the RedCar
if (sprite.Name == "RedCar")
{
// Set the RedCar
RedCar = sprite;
}
else
{
// Set the WhiteCar
WhiteCar = sprite;
}
}
}
Refresh 事件是我移动图像的位置(在我的示例中通过随机数)。
一个提示如果使用的计时器随时间而变,我通常会放置诸如 NotificationInProgress 标志之类的东西,以防一个操作花费的时间超过一秒。
也许在您的用例中,有多个消息是可以的,但有时您需要等待一个完成,然后再完成下一个。
public bool NotificationInProgress { get; set; }
那么在你通知订阅者之前我会测试
if (!NotificationInProgress)
{
// send your message.
}
如果您想查看一个开源 Blazor 示例项目,我在该项目中演示了此代码来自的简单动画,请点击此处:
https://github.com/DataJuggler/DataJuggler.Blazor.Components
也许它会给你一些关于如何安排你的项目的想法。