danrockcoll
danrockcoll

Reputation: 255

How To Get The Results Of A Worker Background Service In C# .NET?

I have used the Worker Service template generated by Visual Studio 2022 as an example, but basically I was wondering what would be a method for finding out the result of a worker run once it is complete and the host has shutdown:-

  public class Program
  {
    public static void Main(string[] args)
    {
      IHost host = Host.CreateDefaultBuilder(args)
          .ConfigureServices(services =>
          {
            services.AddHostedService<Worker>();
          })
          .Build();

      host.Run();

      Console.WriteLine("how do i get the result here?");
    }
  }

  public class Worker : BackgroundService
  {
    private readonly ILogger<Worker> _logger;

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

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
      _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
      await Task.Delay(1000, stoppingToken);

      string result = "it worked, processed some stuff";
      _logger.LogInformation(result);

      // _applicationLifetime.StopApplication() command would be here
      // (haven't added all that wiring to keep code clearer, can just do a ctrl-c to emulate)
    }
  }

In Program.Main, I would like to have the worker result after the host.Run() has completed (where I put the Console.WriteLine) - how can I do this?

Upvotes: 0

Views: 723

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456657

In Program.Main, I would like to have the worker result after the host.Run() has completed (where I put the Console.WriteLine) - how can I do this?

You'll need to save it somewhere, i.e., in a global variable or singleton.

Bear in mind that Ctrl-C (or other exit requests) can cause Run to return before the result is saved, so the result can be null.

Upvotes: 1

Related Questions