C# Event listener from worker service

I have invoked event from endpoint and i need listen from worker service if event is invoked run some method

public class WorkerService : BackgroundService
{
    private readonly ILogger<WorkerService> _logger;
    private readonly IEventService _eventService;

    public WorkerService(ILogger<WorkerService> logger, IEventService eventService)
    {
        _logger = logger;
        _eventService = eventService;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _eventService.RegEvent += Log;
         await Task.Delay(2000);
        _eventService.RegEvent -= Log;

    }

    private void Log(string message)
    {
        _logger.LogInformation("dssd");
    }
}

public interface IEventService
{
    public delegate void RegistrationEvent(string message);

    public event RegistrationEvent RegEvent;
    public void InvokeEvent();

}

public class EventService : IEventService
{
    private readonly ILogger<EventService> _logger;

    public event IEventService.RegistrationEvent RegEvent;

    public EventService(ILogger<EventService> logger)
    {
        _logger = logger;
    }

    public void InvokeEvent()
    {
        RegEvent?.Invoke("Test message");
        _logger.LogInformation($"From {nameof(EventService)}");
    }
}

  • can you please share error details you are getting to be more specific

    – 




  • Unrelated: “logger.LogInformation($”From {nameof(EventService)}”);” – the source of the log comes with the category and microsoft recommends not to use string interpolation in log message templates.

    – 

  • On topic: It’s pretty unclear what the question is but it is clear that this only works for 2 seconds … I guess that’s not what is intended, right? You may be in need of a different service type that providdes you with a start and stop hook, so you can just register the event handler on start and deregister again on stop.

    – 

  • I does not getting sent message from Event Service Maybe I’m doing something wrong

    – 

  • Yes you are: ” ExecuteAsync(CancellationToken) This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.” – that means that the method shall only return, when the service shuts down. You run it for 2 seconds and that’s it.

    – 




Leave a Comment