SignalR:带有计时器的System.ObjectDisposedException [英] SignalR: System.ObjectDisposedException with timer
问题描述
我正在使用signalR,我想每2秒向我的客户发送一条小消息.因此,我遵循了
我可以看到此处:
不要将状态存储在集线器类的属性中.每个集线器方法调用都在一个新的集线器实例上执行.
因此,我决定搜索如何为我的中心创建服务.这就是 Medium 的作用.(下载他们的解决方案,因为他们的教程中遗漏了很多东西)
在我的中心中创建计时器是一种错误的方法.
已解决.
I'm playing with signalR and I want to send every 2s a little message to my clients. So I followed this tutorial, and it works good for chatting, now, I want to implement my timer. Then, I made this (ASP.NET .NET Core 3.1):
public ChatHub()
{
Debug.WriteLine("hello");
var timer1 = new Timer();
timer1.Elapsed += this.Timer1_Elapsed;
timer1.Interval = 2000;
timer1.Start();
}
private async void Timer1_Elapsed(object sender, ElapsedEventArgs e)
{
Debug.WriteLine("tick");
await SendMessage("user", "hello");
}
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
But everytime, I get this error (in this.Clients.Add...):
System.ObjectDisposedException: Cannot access a disposed object.
And I don't understand why, I checked stackoverflow, tried some solutions, but i'm already stuck.
Thank for your help.
Sample: https://github.com/Naografix/SignalRProblem
Stacktrace:
Message = "Cannot access a disposed object.\r\nObject name: 'HomeHub'."
at Microsoft.AspNetCore.SignalR.Hub.CheckDisposed()
at Microsoft.AspNetCore.SignalR.Hub.get_Clients()
at ****.HomeHub.<Timer1_Elapsed>d__1.MoveNext() in *****.Api\Hubs\HomeHub.cs:line 32
I can see here this:
Don't store state in a property on the hub class. Every hub method call is executed on a new hub instance.
So I decided to search how to create a service for my hub. And this is what Medium does. (Download their solution because lot of things are missing in their tutorial)
Creating a timer in my hub was a bad approach.
Solved.
这篇关于SignalR:带有计时器的System.ObjectDisposedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!