C# 通过Web套接字向客户端发送消息。每条消息有不同的时间间隔

C# 通过Web套接字向客户端发送消息。每条消息有不同的时间间隔,c#,asp.net-mvc,sockets,signalr,C#,Asp.net Mvc,Sockets,Signalr,我正在开发一个服务器/客户端应用程序。服务器以一定的时间间隔向客户端推出消息。每条消息可以有不同的时间属性 最好的方法是什么?我可以暂停线程,但这似乎有点粗糙。此场景是否有最佳实践?您可以使用 根据您的标记,我假设您使用的是C#,因此您可以看到about任务类(这实现了线程)假设您想使用signal(您添加了一个标记),一个简单的计时器可以完成这项工作: public sealed class MatchingSupervisor { private static readonly IL

我正在开发一个服务器/客户端应用程序。服务器以一定的时间间隔向客户端推出消息。每条消息可以有不同的时间属性

最好的方法是什么?我可以暂停线程,但这似乎有点粗糙。此场景是否有最佳实践?

您可以使用


根据您的标记,我假设您使用的是C#,因此您可以看到about任务类(这实现了线程)

假设您想使用
signal
(您添加了一个标记),一个简单的计时器可以完成这项工作:

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);
    }
}

您还可以查看本教程:[使用ASP.NET模拟Windows服务以运行计划作业]()这看起来是一个不错的方法。在我的例子中,我有一个场景,比如message1:send然后等待30秒,message2 send然后等待60秒,等等。我应该在计时器初始值设定项的第四个参数中提供这个时间参数吗?这取决于应用程序的逻辑。您是否要同时向所有连接的用户发送这些消息?在这种情况下,您可以在每次发送消息时更改计时器间隔,也可以使用计时器运行一次并创建一个新的计时器间隔。如果您需要以不同的时间间隔向特定用户发送消息,那么这将是一个不同的问题,与将内容从服务器推送到客户机无关。请编辑更改时间间隔的答案
public class Startup
{
    private MatchingSupervisor _conversationManager;

    public void Configuration(IAppBuilder app)
    {
        // TODO app configuration

        // Ensure supervisor starts
        _supervisor = MatchingSupervisor.Instance;
    }
}