我以 Visual Studio 2022 生成的 Worker Service 模板为例,但基本上我想知道在 Worker 运行完成且主机关闭后,找出 Worker 运行结果的方法是什么:-
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)
}
}
在 Program.Main 中,我希望在 host.Run() 完成后(我放置 Console.WriteLine 的位置)获得工作结果 - 我该怎么做?
在 Program.Main 中,我希望在 host.Run() 完成后(我放置 Console.WriteLine 的位置)获得工作结果 - 我该怎么做?
您需要将其保存在某个地方,即在全局变量或单例中。
请记住,Ctrl-C(或其他退出请求)可能导致
Run
返回 before 结果被保存,所以结果可以是 null
.