gpt4 book ai didi

c# - 如何在单独的线程上运行后台服务?

转载 作者:行者123 更新时间:2023-12-05 06:12:58 26 4
gpt4 key购买 nike

我意识到后台服务会阻塞主线程,突然间它会在我的主线程中产生延迟。我找不到有关如何使后台服务不产生延迟和阻塞主线程的有用资源。有什么建议吗?

public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(DoWork, null, 0, 10000);
Initialize().GetAwaiter();

return Task.CompletedTask;
}

private async void DoWork(object state)
{
try
{
//some logic
await testService.DoWorkAsync();
}
catch (Exception ex)
{
Log.Error(ex, "TestBackgroundService DoWork throws ");
}
}


private async Task Initialize()
{
while (true)
{
try
{
if (IsEnabled)
{
//some logic
await testService.PrintAsync();
IsEnabled = false;
}
else
{
//some logic
await testService.CloseAsync();
if (condition)
{
IsEnabled = true;
}
}
await Task.Delay(1000);
}
catch (Exception ex)
{
Log.Error($"ExecuteAsync throws {ex.ToString()}");
}
}
}

最佳答案

你必须以正确的方式使用它,我认为范围内的后台任务是你想要的:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio#consuming-a-scoped-service-in-a-background-task

这里有一个 ExecuteAsync 方法,您可以像这样使用它:

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{

while (!stoppingToken.IsCancellationRequested)
{
//your code

await DoWork(stoppingToken);
Task.Delay(1000);
}
}

关于c# - 如何在单独的线程上运行后台服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63450167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com