.NET-托管服务阻止其余API运行
我有一个后台服务类,可以打开订阅并无限期地监听,我相信这会阻止 API 的其余部分运行。我无法调用端点,swagger 页面永远不会启动,但后台服务会运行。
我在 Program.cs 文件中有 services.AddHostedService
,该类继承了 IHostedService
,并且在继承的 StartAsync
中函数我调用一个打开并侦听订阅的方法。这永远不会结束,因此它会阻塞 API 的其余部分。
我该如何解决这个问题?我需要在 API 启动时永远打开此订阅,但我也需要使用该 API。我知道这很可能是并发问题,但这是我的弱点。
谢谢
I have a background service class that opens a subscriptions and listens indefinitely, and I believe this is stopping the rest of the API from running. I cannot call endpoints, the swagger page never boots up, but the background service runs.
I have services.AddHostedService<BackgroundService>();
in the Program.cs file, and that class inherits IHostedService
, and within the inherited StartAsync
function I call a method that opens and listens to a subscription. This will never end, so it blocks the rest of the API.
How can I solve this problem? I need this subscription to be open when the API starts, forever, but I need to use the API as well. I know it's most likely a concurrency problem but this is a weak point of mine.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以异步地做你的事情。
IHostedServices
的启动正在等待StartAsync(...)
完成。就您而言,我认为您在 StartAsync(...) 中完成所有操作,而这将永远不会完成。
IHostedService 文档
其他答案
You can do your stuff asynchronously.
The startup of
IHostedServices
is waiting untilStartAsync(...)
has completed.In your case I think you do your stuff all in the
StartAsync(...)
which will then never finish.IHostedService Documentation
Other SO Answers
感谢您的反馈!这非常有用。
我最终没有使用这种事情的托管服务,而是将其转移到我在端点中称为的服务中。
虽然它仍然是托管服务,但我通过使用我的方法创建一个新线程,其中包含startasync中的逻辑,从而启动该线程。解决了阻塞问题。
我需要阅读有关线程的更多信息!
thanks for the feedback! It was very useful.
I ended up not going with a HostedService for this kind of thing, moved it into a service that I call in an endpoint.
Whilst it was still a HostedService, I solved it by creating a new Thread with my method containing the logic in StartAsync, starting that Thread. That solved the blocking issue.
I need to read more about Threads!