gpt4 book ai didi

c# - 迁移到 ASP CORE 3 : how to migrate backround services?(通过 AddHostedService 添加的服务卡住 Web 应用程序启动)

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:18 27 4
gpt4 key购买 nike

迁移到 ASP Core3 后,此行卡住了 Web 应用程序启动过程(使用 VS 调试:浏览器已弹出但页面加载从未结束)

serviceCollection.AddHostedService<BackgroundService>();

它适用于 Core 2。

我在 ASP Core3 文档中看不到与 AddHostedService 相关的任何重大更改:

https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio

似乎阻止后台服务器 StartAsync 阻止了 Web 应用程序启动。可能应该在 WebHost 中配置一些东西以使 StartAsync 再次异步?

后台服务代码如下:

public class MyBackgroundService : IHostedService
{
private readonly BackgroundServiceHandle backgroundServiceHandle;
private CancellationTokenSource tokenSource;

public MyBackgroundService (BackgroundServiceHandle backgroundServiceHandle) =>
this.backgroundServiceHandle = backgroundServiceHandle;


public async Task StartAsync(CancellationToken cancellationToken)
{
tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
while (cancellationToken.IsCancellationRequested == false)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken).ConfigureAwait(false);

// IMPORTANT: it seems that next line blocks the web app startup, but why this works in CORE 2?
var taskSettings = backgroundServiceHandle.Dequeue(tokenSource.Token);

// the work
}
catch (OperationCanceledException)
{
// execution cancelled
}
}
}

public Task StopAsync(CancellationToken cancellationToken)
{
tokenSource.Cancel();
return Task.CompletedTask;
}
}

public sealed class BackgroundServiceHandle : IDisposable
{
private readonly BlockingCollection<TaskSettings> blockingCollection;

public BackgroundServiceHandle() => blockingCollection = new BlockingCollection<TaskSettings>();

public void Enqueue(TaskSettings settings) => blockingCollection.Add(settings);

public TaskSettings Dequeue(CancellationToken token) => blockingCollection.Take(token);

public void Dispose()
{
blockingCollection.Dispose();
}
}

最佳答案

将基类从 IHostedService 移动到 BackgroundService并将 StartAsync 移动到protected override async Task ExecuteAsync(CancellationToken cancellationToken) 解决问题

关于c# - 迁移到 ASP CORE 3 : how to migrate backround services?(通过 AddHostedService 添加的服务卡住 Web 应用程序启动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58436732/

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