gpt4 book ai didi

c# - 如何使用带有 .NET Core 的 SignalR 从集线器类使用服务器端计时器?

转载 作者:行者123 更新时间:2023-12-04 17:43:10 24 4
gpt4 key购买 nike

我想在 .NET Core 项目中使用 SignalR 从服务器端应用计时器。我可以使用自定义类启动计时器。计时器应在单击停止按钮时停止,并在单击开始按钮时启动。这只是我正在创建的一个演示,就像开始和停止 watch 一样。

我已经使用 Node.js 实现了相同的功能,我没有遇到任何问题。在带有 .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");
}
}

打电话时 StopTimer来自客户端的方法,我没有得到当前的计时器。如果有人能指导我这一点,我将不胜感激。

谢谢
编码意味着问题意味着乐趣。 :)

最佳答案

存储对 timer 的引用在 static ConcurrentDictionaryConnectionId 索引.

您只需要添加 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);

// ...
}
}

关于c# - 如何使用带有 .NET Core 的 SignalR 从集线器类使用服务器端计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53535566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com