C#C
C#2y ago
xriba

✅ Hosted Service running as Windows Service

I have an application running as a Windows Service and I'd like to run some code after the system starts and before it shuts down.

I have tried using HostedServices and everything works fine if I manually start and stop the service. However, it does not work when starting or shutting down the system.

Here is a simplified version of my service, I can also provide an .exe if necessary.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Net.WebSockets;
using System.Text;

const string LOG4NET_CONFIG = "log4net.config";

var builder = Host.CreateApplicationBuilder();

builder.Services.AddWindowsService();
builder.Logging.AddLog4Net(LOG4NET_CONFIG);
builder.Services.AddHostedService<CustomHostedService>();

var host = builder.Build();

host.Run();


class CustomHostedService : IHostedService
{
    private readonly ClientWebSocket _webSocket;
    private readonly ILogger<CustomHostedService> _logger;

    private bool Connected => _webSocket.State is WebSocketState.Open;

    public CustomHostedService(ILogger<CustomHostedService> logger)
    {
        _logger = logger;
        _webSocket = new ClientWebSocket();
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var uri = new Uri("wss://echo.websocket.org");
        await _webSocket.ConnectAsync(uri, cancellationToken);
        Task.Run(ProcessDataAsync, cancellationToken);
    }

    private async Task ProcessDataAsync()
    {
      //...
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Shutting down");

        if (_webSocket.State is WebSocketState.Open || _webSocket.State is WebSocketState.Connecting)
            await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken);
    }
}


During StartAsync I'm executing a network call, but upon reviewing the logs after booting the system, I see this exception:
System.Net.Http.HttpRequestException: No such host is known. (Presumably a DNS error due to host not being resolved yet.)
Followed by the Application Started event.

Additional details:

Category: Microsoft.Extensions.Hosting.Internal.Host
EventId: 11

Hosting failed to start

Exception: 
System.Net.WebSockets.WebSocketException (0x80004005): Unable to connect to the remote server
 ---> System.Net.Http.HttpRequestException: No such host is known. (echo.websocket.org:443)
 ---> System.Net.Sockets.SocketException (11001): No such host is known.
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
   at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|285_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---


As for StopAsync, I believe the method is not executing as I see no logs at all.
Was this page helpful?