コード例 #1
0
        public async Task ExecuteResultAsync(ActionContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var cancellationToken = context.HttpContext.RequestAborted;

            _httpContext = context.HttpContext;
            _httpContext.Response.ContentType           = "text/plain";
            _httpContext.Response.Headers["Connection"] = "close";
            await _httpContext.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);

            _dispatcher.Attach(this);

            try
            {
                var utf8Bytes = JsonSerializer.SerializeToUtf8Bytes(new Message
                {
                    MessageType = MessageType.Heartbeat
                });

                while (!cancellationToken.IsCancellationRequested)
                {
                    await Task.Delay(TimeSpan.FromSeconds(35), cancellationToken).ConfigureAwait(false);
                    await SendAsync(utf8Bytes, cancellationToken).ConfigureAwait(false);
                }
            }
            catch (TaskCanceledException)
            {
                // This is fine.
            }
            finally
            {
                _dispatcher.Detach(this);
            }
        }