我修改了SignalR网站文档中的广播示例,不再使用随机值,而是读取随机的xml文件。我使用
感谢您。
HttpContext.Current.Server.MapPath
方法访问文件,避免硬编码物理路径。这在Windows 7 IIS 7.5和Visual Studio 2013中运行良好,但在Windows 8.1和Windows Server 2012中发现HttpContext.Current
为null
。在提问之前,我搜索了其他问题,但没有找到类似于这里发生的情况。
下面是整个类的代码:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace SignalRDisplayXML
{
public struct ReturnDataScheme
{
public List<VsDisplaySlotBean> slotsdata;
public string filename;
}
public class XmlTicker
{
private readonly static Lazy<XmlTicker> _instance =
new Lazy<XmlTicker>(() => new XmlTicker(GlobalHost.ConnectionManager.GetHubContext<DisplayXMLHub>().Clients, HttpContext.Current.Server.MapPath("~/Data/")));
private DAO _dao = new DAO();
private ReturnDataScheme _server_data = new ReturnDataScheme();
private string _directoryPath = string.Empty;
private readonly object _processRandomXMLLock = new object();
private volatile bool _updatingRandomXML = false;
private readonly Timer _timer;
private XmlTicker(IHubConnectionContext clients, string path)
{
Clients = clients;
_directoryPath = path;
_server_data.filename = GetRandomFileName();
_server_data.slotsdata = _dao.GetVesselAll(_server_data.filename);
_timer = new Timer(ProcessRandomXML, null, 10000, 10000);
}
public static XmlTicker Instance
{
get
{
return _instance.Value;
}
}
private IHubConnectionContext Clients
{
get;
set;
}
public ReturnDataScheme GetCurrentData()
{
return _server_data;
}
private void ProcessRandomXML(object state)
{
lock (_processRandomXMLLock)
{
if (!_updatingRandomXML)
{
_updatingRandomXML = true;
_server_data.filename = GetRandomFileName();
_server_data.slotsdata = _dao.GetVesselAll(_server_data.filename);
Clients.All.DataPush(_server_data);
_updatingRandomXML = false;
}
}
}
private string GetRandomFileName()
{
Random randomizer = new Random(DateTime.Now.Millisecond);
return _directoryPath + "DisplaySlotFDMF00" + randomizer.Next(1, 9).ToString() + ".xml";
}
}
}
感谢您。