假设我们在默认的Blazor Server中有这个简单的经典计时器。
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
Console.WriteLine($"Count incremented: {currentCount}");
}
private Timer timer;
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
timer = new Timer();
timer.Interval = 1000;
timer.Elapsed += OnTimerInterval;
timer.AutoReset = true;
// Start the timer
timer.Enabled = true;
}
base.OnAfterRender(firstRender);
}
private void OnTimerInterval(object sender, ElapsedEventArgs e)
{
IncrementCount();
InvokeAsync(() => StateHasChanged());
}
public void Dispose()
{
// During prerender, this component is rendered without calling OnAfterRender and then immediately disposed
// this mean timer will be null so we have to check for null or use the Null-conditional operator ?
timer?.Dispose();
}
}
现在,当我在浏览器中打开此页面时,每个新窗口的时间都从零开始(按预期)。但是,我想在浏览器中打开多个页面,并且每个页面都应该看到相同的时间(如果在我的第一个窗口中显示的时间是10,而我打开一个新窗口,则我希望两个窗口的时间都相同)。我该如何实现?
总的来说,我想创建一个简单的SPA,向用户显示实时股票价格值。任何建议,将不胜感激。
SignalR可能是此问题的首选Microsoft解决方案,因为它为应用程序提供了实时Web功能。
在较高的级别上,您需要:
Hub
在服务器上创建一个负责处理与客户端的连接并广播消息(在您的情况下为股票信息)的服务器。IHubContext
通过来向客户端发布更新Hub
。HubConnection
来接收来自服务器的消息。这是使用类似方法的聊天应用程序的完整示例:https : //docs.microsoft.com/zh-cn/azure/azure-signalr/signalr-tutorial-build-blazor-server-chat-app
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句