我正在开发一个服务器/客户端应用程序。服务器以定时间隔向客户端发送消息。每条消息都可以有不同的时间属性。
最好的方法是什么?我可以暂停线程,但这似乎有点hacky。这种情况有最佳实践吗?
答案 0 :(得分:1)
假设你想使用SignalR
(你添加了一个标签),一个简单的计时器可以完成这项工作:
public sealed class MatchingSupervisor
{
private static readonly ILog Log = LogManager.GetLogger(typeof(MatchingSupervisor));
private readonly IHubContext _hub;
private readonly Timer _timer;
#region Singleton
public static MatchingSupervisor Instance => SupervisorInstance.Value;
// Lazy initialization to ensure SupervisorInstance creation is threadsafe
private static readonly Lazy<MatchingSupervisor> SupervisorInstance = new Lazy<MatchingSupervisor>(() =>
new MatchingSupervisor(GlobalHost.ConnectionManager.GetHubContext<YourHubClass>()));
private MatchingSupervisor(IHubContext hubContext)
{
_hub = hubContext;
_timer = new Timer(Run, null, 0, Timeout.Infinite);
}
#endregion
private async void Run(object state)
{
// TODO send messages to clients
// you can use _timer.Change(newInterval, newInterval) here
// if you need to change the next interval
var newInterval = TimeSpan.FromSeconds(60);
_timer.Change(newInterval, newInterval);
}
}
为了确保在系统或应用程序重新启动(系统停机,应用程序回收等)时重新启动计时器,您应该在Owin Startup类上获得一个实例:
public class Startup
{
private MatchingSupervisor _conversationManager;
public void Configuration(IAppBuilder app)
{
// TODO app configuration
// Ensure supervisor starts
_supervisor = MatchingSupervisor.Instance;
}
}
答案 1 :(得分:0)
您可以使用Quartz.NET。
通过你的标签,我想你正在使用C#,所以你可以看到关于任务类的Microsoft doc(这实现了线程)