Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何以编程方式停止HostedService?_C#_Asp.net Core_Asp.net Core Hosted Services - Fatal编程技术网

C# 如何以编程方式停止HostedService?

C# 如何以编程方式停止HostedService?,c#,asp.net-core,asp.net-core-hosted-services,C#,Asp.net Core,Asp.net Core Hosted Services,我正在构建一个dotnet核心托管服务应用程序。一段时间后我需要停止申请 我怎样才能阻止它 我已经尝试添加到StartAsync方法中 await Task.Delay(5000); Environment.Exit(0); 主要内容: static Task Main(字符串[]args) { var hostBuilder=new hostBuilder() .ConfigureServices((主机上下文,服务)=> { services.AddHostedService(); })

我正在构建一个dotnet核心托管服务应用程序。一段时间后我需要停止申请

我怎样才能阻止它

我已经尝试添加到StartAsync方法中

await Task.Delay(5000);
Environment.Exit(0);
主要内容:

static Task Main(字符串[]args)
{
var hostBuilder=new hostBuilder()
.ConfigureServices((主机上下文,服务)=>
{
services.AddHostedService();
})
.UseLogging();
返回hostBuilder.RunConsoleAsync();
}
它不起作用。如何正确停止它?

接受
CancellationToken
。您可以创建一个
CancellationTokenSource
,在给定的毫秒数后发出取消信号:

var cancellationTokenSource = new CancellationTokenSource(5000);

return hostBuilder.RunConsoleAsync(cancellationTokenSource.Token);
这样,应用程序将在大约五秒钟后关闭

var cancellationTokenSource = new CancellationTokenSource(5000);

return hostBuilder.RunConsoleAsync(cancellationTokenSource.Token);