.NET Core通用主机中的BackgroundService任务未在单独的线程上运行 [英] BackgroundService tasks not running on separate threads in .NET Core Generic Host

查看:1582
本文介绍了.NET Core通用主机中的BackgroundService任务未在单独的线程上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的.NET Core通用主机似乎是实现运行多个并发任务的控制台应用程序的不错选择。与其明确地创建和运行任务,不如我可以使用IHostedService(或BackgroundService)将它们定义为服务。但是,通用主机正在同一线程上执行所有我所谓的后台任务。这是预期的行为吗?

The new .NET Core "Generic Host" seemed like a good choice for implementing a console application that runs several concurent tasks. Rather than explicitly creating and running the tasks, I thought I could define them as services using IHostedService (or BackgroundService). However, the Generic Host is executing all my so-called "background tasks" on the same thread. Is this the intended behavior?

public static async Task Main(string[] args)
    {
        var host = new HostBuilder()
        .ConfigureHostConfiguration(...)
        .ConfigureAppConfiguration(...)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddLogging();
            services.AddHostedService<Service1>();
            services.AddHostedService<Service2>();
            services.AddHostedService<Service3>();
        })
        .ConfigureLogging(...)
        .UseConsoleLifetime()
        .Build();

        await host.RunAsync();
    }

通用主机在同一线程上运行所有三个后台服务。在主线程上以及每个后台服务的StartAsync或ExecuteAsync方法中,发现 Thread.CurrentThread.ManagedThreadId 等于1。有没有办法确保服务在单独的线程上运行?

The Generic Host runs all three of my "background" services on the same thread. Thread.CurrentThread.ManagedThreadId was found to equal 1 on the Main thread and within the StartAsync or ExecuteAsync methods of each of the "background" services. Is there a way to ensure that the services run on separate threads?

推荐答案

IHostedService接口仅为您提供启动和停止的挂钩你的工作。您负责根据服务的工作自行实施线程,后台事件等。您可以设置一个计时器来异步执行事件,也可以设置一个正在运行的后台线程等。

The IHostedService interface only gives you hooks for starting and stopping your work. you are responsible for implementing threading, background events etc. yourself based on what your service does. You could set up a timer that executes events asynchronously or set up a running background thread etc.

通用主机并不意味着服务具有线程或执行模型。

The generic host does not imply a threading or execution model for your "services".

这篇关于.NET Core通用主机中的BackgroundService任务未在单独的线程上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆