ExportClient
班级有OnTickRecieved
事件,这可以帮助我接收一些数据(来自市场的出价)。我想要的只是在浏览器中的图表上实时接收这些数据。当我按下Go
UI 端的按钮,它调用Go()
控制器中的方法,然后什么也没有发生。这是合乎逻辑的 - 因为在服务器上发出请求后,控制器被销毁。
我的问题是:如何强制服务器不断向我发送事件数据?
控制器 code:
public class ChartsController : Controller
{
[HttpGet]
public void Go()
{
var exportClient = new ExportClient();
exportClient.TickRecieved += exportClient_TickRecieved;
}
private void exportClient_TickRecieved(object sender, TickRecievedEventArgs args)
{
ImpulserHub.SendBidPrice(args.Bid);
}
}
Hub code:
[HubName("impulserHub")]
public class ImpulserHub : Hub
{
public static void SendBidPrice(double bid)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ImpulserHub>();
hubContext.Clients.All.sendBidPrice(bid);
}
}
我已经测试了 SignalR,这段代码工作正常:
[HttpGet]
public void Go()
{
ImpulserHub.SendBidPrice(3.3333333); // I have received this number on UI
}
最简单的方法是将导出客户端作为单例或静态变量,并在全局范围内(可能在您的Application_Start()
来自 Global.asax.cs 的方法)。您的集线器代码也应该移出,因为集线器像控制器一样是瞬态的。
它看起来是这样的:
private ExportClient _exportClient;
private IHubContext _impulserHub;
protected void Application_Start()
{
_exportClient = new ExportClient();
exportClient.TickRecieved += exportClient_TickRecieved;
_impulserHub = GlobalHost.ConnectionManager.GetHubContext<ImpulserHub>();
}
private void exportClient_TickRecieved(object sender, TickRecievedEventArgs args)
{
_impulserHub.Clients.All.sendBidPrice(args.Bid);
}
这段代码仍然存在一个问题。 IIS 将拆除未主动接收请求的网站。这意味着即使事件被触发,代码也可能随时停止工作。管理应用程序拆卸很困难,因为必须在应用程序启动和停止之间保存/传输状态。除非您可以将 IIS 设置为永不拆除您的应用程序(大多数情况下在共享或云托管上不可能),否则您应该尝试使用HangFire http://hangfire.io/库,可作为努吉特包 https://www.nuget.org/packages/HangFire/它是专门为该用例设计的,经过一些重构,您的代码可能如下所示:
private ExportClient _exportClient;
private IHubContext _impulserHub;
protected void Application_Start()
{
_exportClient = new ExportClient();
exportClient.TickRecieved += exportClient_TickRecieved;
_impulserHub = GlobalHost.ConnectionManager.GetHubContext<ImpulserHub>();
BackgroundJob.Schedule(() => _impulserHub.Clients.All.sendBidPrice(_exportClient.GetBid()), TimeSpan.FromSeconds(5));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)