【问题标题】:Only the first of multiple hosted services is being started只有多个托管服务中的第一个正在启动
【发布时间】:2020-10-26 22:16:49
【问题描述】:

我试图弄清楚如何让 ASP.NET Core 3.1 启动多个托管服务,以便我可以在后台定期运行一些东西。我已经阅读了大量类似的问题(例如,this one),据我所知,立即从StartAsync() 返回任务很重要。这也是 BackgroundService 类 is implemented 中的 StartAsync() 的方式。

但是,即使我将自己的代码减少到最低限度,也只会执行第一个注册的服务(阅读:关闭服务器时正确启动和停止):

type Foo() =
    interface IHostedService with
        member this.StartAsync ct =
            printfn "Start Foo"
            Task.CompletedTask
            
        member this.StopAsync ct =
            printfn "Stop Foo"
            Task.CompletedTask
            
type Bar() =
    interface IHostedService with
        member this.StartAsync ct =
            printfn "Start Bar"
            Task.CompletedTask
            
        member this.StopAsync ct =
            printfn "Stop Bar"
            Task.CompletedTask
let configureServices (services : IServiceCollection) =
    services
        .AddHostedService<Foo>()
        .AddHostedService<Bar> |> ignore

当应用程序启动时,这会导致:

watch : Started
Start Foo
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://[::]:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
^Cwatch : info: Microsoft.Hosting.Lifetime[0]
      Application is shutting down...
Shutdown requested. Press Ctrl+C again to force exit.
Stop Foo
watch : Exited

所以我的问题是:我遇到了错误,还是错过了什么?

【问题讨论】:

    标签: asp.net-core .net-core f#


    【解决方案1】:

    我认为你需要调用该函数

    AddHostedService&lt;Bar&gt;() 而不是AddHostedService&lt;Bar&gt;

    let configureServices (services : IServiceCollection) =
         services
             .AddHostedService<Foo>()
             .AddHostedService<Bar>() |> ignore
    

    输出:

    Start Foo
    Start Bar
    info: Microsoft.Hosting.Lifetime[0]
          Now listening on: http://localhost:5000
    info: Microsoft.Hosting.Lifetime[0]
          Application started. Press Ctrl+C to shut down.
    info: Microsoft.Hosting.Lifetime[0]
          Hosting environment: Development
    info: Microsoft.Hosting.Lifetime[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2018-04-12
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多