问题
I'm using signalR to send data to clients from server. What I want to is check data in the table(MSSQL DB) and send the related data to clients through signalR. So I want to create some background service to check database and send data.
I planned to use
System.Threading.Thread.Sleep(3000);
with
while(true)
loop. How can I create service class to run this method in startup.
Is there any method to use do this task in standard way??
回答1:
You can use an IHostedService
and IHubContext
to accomplish this.
See the doc on background services with ASP.NET Core:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.1
See the doc on IHubContext
:
https://docs.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-2.1
Here's an example of using both together:
https://github.com/davidfowl/UT3/blob/fb12e182d42d2a5a902c1979ea0e91b66fe60607/UTT/Scavenger.cs
And the wire up:
https://github.com/davidfowl/UT3/blob/fb12e182d42d2a5a902c1979ea0e91b66fe60607/UTT/Startup.cs#L46
来源:https://stackoverflow.com/questions/52251688/asp-net-core-background-service-to-send-data-through-signalr