在ASP.NET MVC時代,要在網站上掛背景程式,需要透過第三方套件來達成,如今ASP.NET內建IHostedService這個介面,透過它即可達成目的,實作方式也不算太難,以下是程式碼:

首先是實作IHostedService,其中StartAsyncStopAsync為主要要實作的method。

public class DemoTask : IHostedService, IDisposable
{
    public static ConcurrentBag<LogItem>? Queue;

    private Timer? _timer = null;

    Task IHostedService.StartAsync(CancellationToken cancellationToken)
    {
        Queue = new ConcurrentBag<LogItem>();
        _timer = new Timer(DoJob, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        return Task.CompletedTask;
    }

    Task IHostedService.StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    private void DoJob(object? state)
    {
        LogItem? item = null;
        Queue?.TryTake(out item);
        Console.WriteLine($"ID: {item?.RequestID}, Content: {item?.Content}");
    }

    public void Dispose()
    {

    }
}

其中DoJob只是單純的把內容輸出到螢幕上,之後就是註冊該類別:

builder.Services.AddHostedService<DemoTask>();

之後在controller加一個API,讓它可以塞內容到list,測試這個的目的只要是最近想找出一個log資訊的方法,且不想讓它影響到程式的執行,透過這方式,即使做log的部份出問題,整個流程也不會中斷:

public IActionResult Insert()
{
    LogItem item = new LogItem
    {
        Content = DateTime.Now.ToString(),
        RequestID = Guid.NewGuid().ToString(),
    };
    DemoTask.Queue?.Add(item);
    return Content(DateTime.Now.ToString());
}

參考資料