我试图在.Net Core中优雅地关闭Azure webjobs。现在我创建了一个名为GracefulShutdown的类,如下所示。我把这个班级注册为单身人士。在program.cs中我使用这个类启动webjob。在我的工作中,我得到同一个班级来检查是否要求关机。但我得到的价值总是假的。我认为这里有一些多线程的事情,但我不确定。我做错了什么?
Program.cs的
...
serviceCollection.AddSingleton<IGracefulShutdown, GracefulShutdown>();
...
var gracefulShutdown = serviceProvider.GetService<IGracefulShutdown>();
...
gracefulShutdown.StartJob(config);
GracefulShutdown.cs
public class GracefulShutdown : IGracefulShutdown
{
private bool gracefulShutdown;
public bool CheckGracefulShutdownStatus()
{
return gracefulShutdown;
}
public void StartJob(JobHostConfiguration configuration)
{
using (var jobHost = new JobHost(configuration))
{
Environment.SetEnvironmentVariable("WEBJOBS_SHUTDOWN_FILE", Directory.GetCurrentDirectory());
WebJobsShutdownWatcher watcher = new WebJobsShutdownWatcher();
gracefulShutdown = false;
Task.Run(() => {
jobHost.Start();
while (!gracefulShutdown)
{
if (watcher.Token.IsCancellationRequested)
{
gracefulShutdown = true;
System.Threading.Thread.Sleep(50000);
}
}
}, watcher.Token).Wait();
}
}
}
ProcessorJob.cs
...
private readonly IGracefulShutdown gracefulShutdown;
...
public ProcessorJob(IGracefulShutdown gracefulShutdown)
{
this.gracefulShutdown = gracefulShutdown;
}
...
if (gracefulShutdown.CheckGracefulShutdownStatus())
{
return;
}
答案 0 :(得分:0)
我的单例具有不同值的问题是在program.cs中调用了两次serviceCollection.BuildServiceProvider()。 当然这不是必需的,并且在重构之后代码可以工作。
我还将布尔变量gracefulShutdown更改为属性。