简体   繁体   English

如何使用带有.NET Core的SignalR的Hub类的服务器端Timer?

[英]How to use server-side Timer from Hub class using SignalR with .NET Core?

I want to apply timer from server side using SignalR in .NET Core project. 我想在.NET Core项目中使用SignalR从服务器端应用计时器。 I am able to start timer with custom class. 我可以使用自定义类启动计时器。 Timer should be stopped on Stop button click and started on Start button click. 计时器应在“停止”按钮单击时停止,并在“开始”按钮单击时开始。 It is just a demo I am creating like start and stop watch. 这只是我正在制作的演示,如开始和停止观看。

I have implemented the same using Node.js and I got no problem. 我已经使用Node.js实现了相同的操作,但没有问题。 In SignalR with .NET Core, it is just I am not able to get the same. 在带有.NET Core的SignalR中,只是我无法获得相同的结果。

// Custom Timer class to be able to access HubCallerContext and Clients
public class CustomTimer : System.Timers.Timer
{
    public CustomTimer(double interval)
        : base(interval)
    {
    }

    public HubCallerContext callerContext { get; set; }
    public IHubCallerClients<IClient> hubCallerClients { get; set; }
}
public class ApplicationHub : Hub<IClient>
{
    public CustomTimer timer = new CustomTimer(1000);

    // This method will be called on Start button click
    public async Task StartTime()
    { 
        timer.callerContext = Context;
        timer.hubCallerClients = Clients;
        timer.Elapsed += aTimer_Elapsed;
        timer.Interval = 1000;
        timer.Enabled = true;
    }

    // This method will pass time to all connected clients
    void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        timer = (CustomTimer)sender;
        HubCallerContext hcallerContext = timer.callerContext;
        IHubCallerClients<IClient> hubClients = timer.hubCallerClients;

        hubClients.Clients.All.ShowTime(DateTime.Now.Hour.ToString() +
            ":" + DateTime.Now.Minute.ToString() + ":" +
            DateTime.Now.Second.ToString());
    }

    // This should stop running timer on button click event from client
    public async Task StopTime()
    {
        timer.Elapsed -= aTimer_Elapsed;
        timer.Enabled = false;

        await Clients.All.StopTime("Timer Stopped");
    }
}

While calling StopTimer method from client, I am not getting current timer. 从客户端调用StopTimer方法时,我没有得到当前计时器。 If any one can guide me with this, I would be grateful. 如果有人可以指导我,我将不胜感激。

Thanks 谢谢
Coding means issues means fun. 编码意味着问题意味着乐趣。 :) :)

Store a reference to timer in a static ConcurrentDictionary indexed by ConnectionId . 将对timer的引用存储在由ConnectionId索引的static ConcurrentDictionary

You just need to add 3 lines and change 2 lines. 您只需要添加3行并更改2行即可。

public class CustomTimer : System.Timers.Timer
{
    // Add this ↓
    public static ConcurrentDictionary<string, CustomTimer> Timers = new ConcurrentDictionary<string, CustomTimer>();

    // ...
}
public class ApplicationHub : Hub<IClient>
{
    public CustomTimer timer = new CustomTimer(1000);

    // Change this ↓ to `static`, so that `timer.Elapsed -= aTimer_Elapsed;` works
    static void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        // Change this ↓ to `var`
        var timer = (CustomTimer)sender;

        // ...
    }

    public async Task StartTime()
    {
        // Add this ↓
        timer = CustomTimer.Timers.GetOrAdd(Context.ConnectionId, timer);

        // ...
    }

    public async Task StopTime()
    {
        // Add this ↓
        timer = CustomTimer.Timers.GetOrAdd(Context.ConnectionId, timer);

        // ...
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在服务器端捕获 ASP.NET Core 2 SignalR 异常并在客户端使用 JavaScript 处理它们? - How to catch ASP.NET Core 2 SignalR exceptions on server-side and handle them on client side with JavaScript? 如何在ASP.NET Core应用程序中将记录器传递到服务器端的SignalR集线器 - How to pass logger into SignalR hub on server side in ASP.NET Core application 如何在 ASP.NET Core 2.2 中使用来自不同托管项目的共享 SignalR Hub - How to use shared SignalR Hub from different hosted project in ASP.NET Core 2.2 SignalR 集线器从服务器端关闭连接 - SignalR Hub close connection from server side 如何在带有 Razor 页面的 ASP.NET Core 2.1 中使用或处理不是为并发而设计的服务器端 SDK - How to Use or Deal With Server-Side SDKs not Designed for Concurrency in ASP.NET Core 2.1 with Razor Pages 如何将EventHandler与具有.NET核心的SignalR集线器结合? - How to combine an EventHandler with a SignalR hub with .NET core? 如何使用 .NET 核心在服务器端评估 JavaScript 表达式服务器端? - How do I evaluate JavaScript expressions server-side using .NET Core? SignalR - 用于检测客户端是否与集线器断开连接的服务器端方法? - SignalR - Server side method to detect if a client disconnects from a hub? 如何在 ASP.NET Core 3.1 MVC 中进行RequiredIf 客户端和服务器端验证? - How to make RequiredIf Client-side and server-side validation in ASP.NET Core 3.1 MVC? 来自客户端的集线器方法未在ASP.NET Core SignalR中调用 - Hub method from client is not invoking in ASP.NET Core SignalR
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM