相关疑难解决方法(0)

Asp.Net核心长期运行/后台任务

以下是在Asp.Net Core中实现长时间运行后台工作的正确模式吗?或者我应该使用某种形式的Task.Run/ TaskFactory.StartNewwith TaskCreationOptions.LongRunning选项?

    public void Configure(IApplicationLifetime lifetime)
    {
        lifetime.ApplicationStarted.Register(() =>
        {
            // not awaiting the 'promise task' here
            var t = DoWorkAsync(lifetime.ApplicationStopping);

            lifetime.ApplicationStopped.Register(() =>
            {
                try
                {
                    // give extra time to complete before shutting down
                    t.Wait(TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    // ignore
                }
            });
        });
    }

    async Task DoWorkAsync(CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            await // async method
        }
    }
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core

18
推荐指数
2
解决办法
1万
查看次数

在Self Hosted ASP.NET Core Microservice中启动多个后台线程

我在哪里可以创建多个长时间运行的后台线程,Self Hosted Self Contained ASP.NET Core Microservice其生命周期与微服务生命周期相同?因此,从线程检索的信息可以作为对请求的响应发送.

尝试给定代码,但它在后台线程忙时减少了http请求性能.Program.cs文件的主要方法是:

static void Main(string[] args)
{
    //Start background thread1
    //Start background thread2
    //Around 10 background threads
    //Start host
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseUrls(ServerUrl)
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .ConfigureServices(s => s.AddRouting())
        .Configure(app => app.UseRouter(r => { (new Router()).Route(r); }))
        .Build();
    host.Run();
}
Run Code Online (Sandbox Code Playgroud)

线程以这种方式工作:

Thread t1 = new Thread(StartWork);
t1.IsBackground = true;
t1.Start();

public void StartWork()
{
    while (ApplicationIsRunning)
    {
        //Get database info >> login into remote devices (SSH) >> get information …
Run Code Online (Sandbox Code Playgroud)

c# multithreading .net-core kestrel-http-server asp.net-core

1
推荐指数
2
解决办法
4895
查看次数