簡體   English   中英

我應該在哪里開始ASP.NET Core中的持久后台任務?

[英]Where am I supposed to start persistent background tasks in ASP.NET Core?

在我的Web應用程序(ASP.NET Core)中,我想在后台運行一個正在偵聽遠程服務器的作業,計算一些結果並將其推送到Pusher上的客戶端(websocket)。

我不確定我應該在哪里開始這個任務。 目前我在最后開始

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)

Startup.cs中

但我覺得這有點不對,在一個名為“Configure”的方法中啟動后台作業是沒有意義的。 我期待在某個地方找到一個Start方法

此外,當我嘗試使用EF Core 生成初始數據庫遷移文件時 ,它實際上執行該方法並啟動我的任務..這顯然沒有任何意義:

dotnet ef migrations add InitialCreate

從控制台運行它會創建遷移代碼,該代碼將用於根據我的數據模型在SQL Server上創建數據庫。

為什么沒有一種方法可以開始一個任務? 我不希望這是一個單獨的進程,它實際上不需要自己的進程,它本質上是Web服務器的一部分,因為它確實通過websocket與客戶端(瀏覽器)進行通信,所以它是有道理的將其作為Web服務器的一部分運行。

我相信你在尋找這個

https://blogs.msdn.microsoft.com/cesardelatorre/2017/11/18/implementing-background-tasks-in-microservices-with-ihostedservice-and-the-backgroundservice-class-net-core-2-x/

我做了一個2小時的自我屢獲殊榮的黑客馬拉松對我自己去學習。

https://github.com/nixxholas/nautilus

您可以在此處參考注射並從那里實施摘要。

許多MVC項目並不是真正需要運行持久性后台任務。 這就是為什么你沒有看到他們通過模板烘焙到一個全新的項目。 最好為開發人員提供一個界面來點擊並繼續使用它。

此外,關於為這些后台任務打開該套接字連接,我還沒有為此建立解決方案。 據我所知/做過,我只能將有效負載廣播到連接到我自己的socketmanager的客戶端,因此你必須在其他地方查找。 如果在IHostedService中有關於websockets的任何內容,我肯定會發出嗶嗶聲。

好吧無論如何這里發生了什么。

把它放在項目的某個地方,它更多的是一個讓你重載以創建自己的任務的界面

/// Copyright(c) .NET Foundation.Licensed under the Apache License, Version 2.0.
    /// <summary>
    /// Base class for implementing a long running <see cref="IHostedService"/>.
    /// </summary>
    public abstract class BackgroundService : IHostedService, IDisposable
    {
        protected readonly IServiceScopeFactory _scopeFactory;
        private Task _executingTask;
        private readonly CancellationTokenSource _stoppingCts =
                                                       new CancellationTokenSource();

        public BackgroundService(IServiceScopeFactory scopeFactory) {
            _scopeFactory = scopeFactory;
        }

        protected abstract Task ExecuteAsync(CancellationToken stoppingToken);

        public virtual Task StartAsync(CancellationToken cancellationToken)
        {
            // Store the task we're executing
            _executingTask = ExecuteAsync(_stoppingCts.Token);

            // If the task is completed then return it,
            // this will bubble cancellation and failure to the caller
            if (_executingTask.IsCompleted)
            {
                return _executingTask;
            }

            // Otherwise it's running
            return Task.CompletedTask;
        }

        public virtual async Task StopAsync(CancellationToken cancellationToken)
        {
            // Stop called without start
            if (_executingTask == null)
            {
                return;
            }

            try
            {
                // Signal cancellation to the executing method
                _stoppingCts.Cancel();
            }
            finally
            {
                // Wait until the task completes or the stop token triggers
                await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite,
                                                              cancellationToken));
            }
        }

        public virtual void Dispose()
        {
            _stoppingCts.Cancel();
        }
    }

以下是您實際使用它的方法

public class IncomingEthTxService : BackgroundService
    {
        public IncomingEthTxService(IServiceScopeFactory scopeFactory) : base(scopeFactory)
        {
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

            while (!stoppingToken.IsCancellationRequested)
            {
                using (var scope = _scopeFactory.CreateScope())
                {
                    var dbContext = scope.ServiceProvider.GetRequiredService<NautilusDbContext>();

                    Console.WriteLine("[IncomingEthTxService] Service is Running");

                    // Run something

                    await Task.Delay(5, stoppingToken);
                }
            }
        }
    }

如果你注意到,那里有獎金。 您必須使用服務范圍才能訪問數據庫操作,因為它是一個單例。

注入您的服務

// Background Service Dependencies
            services.AddSingleton<IHostedService, IncomingEthTxService>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM