1

我已经开始使用 .NET Core 托管服务来处理一些发布/订阅功能。我计划使用取消令牌来关闭服务。我想知道他们是否有一些超时?如果服务没有被明确停止,我希望它永远运行。

感谢你的帮助。

        protected override Task ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.Factory.StartNew(
            () =>
            {
                var redisPubSub = new RedisPubSubServer(ClientsManager, Constants.RedisChannel)
                {
                    OnMessage = (channel, msg) =>
                    {
                        Trace.WriteLine($"Received '{msg}' from channel '{channel}'");
                        var message = JsonConvert.DeserializeObject<Message>(msg);                          
                            _hubContext.Clients.User(message.UserId.ToString()).SendAsync("ReceiveMessage", message, cancellationToken);
                    },
                    OnUnSubscribe = (message) =>
                    {
                        Trace.WriteLine($"OnUnSubscribe returns {message}");
                    },
                    OnError = (exception) =>
                    {
                        Trace.WriteLine($"OnError returns {exception}");
                    },
                    OnStart = () =>
                    {
                        Trace.WriteLine($"OnStart has been fired.");
                    },
                    OnStop = () =>
                    {
                        Trace.WriteLine($"OnStop has been fired");
                    }
                };

                redisPubSub.Start();
                Trace.WriteLine($"OnStop has been fired {redisPubSub.WaitBeforeNextRestart}  {redisPubSub.HeartbeatTimeout}  {redisPubSub.HeartbeatInterval}");
            }, cancellationToken);
    }
4

1 回答 1

0

如果您在此处查看我接受的答案,并且您的托管服务看起来像这样,您可以在ExecuteAsync方法中包含的 while 循环中执行以下操作。

await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);

当然,该方法必须标记为异步。

于 2018-08-06T15:12:39.583 回答