1. 如何在 .Net Core 中使用 IHostedService

        共 3086字,需瀏覽 7分鐘

         ·

        2021-01-26 17:22

        在我們應(yīng)用程序中常常會(huì)有一些執(zhí)行后臺(tái)任務(wù)和任務(wù)調(diào)度的需求,那如何在 ASP.Net Core 中實(shí)現(xiàn)呢?可以利用 Azure WebJobs 或者其他一些第三方任務(wù)調(diào)度框架,如:QuartzHangfire。

        在 ASP.Net Core 中,也可以將 后臺(tái)任務(wù) 作為托管服務(wù)的模式,所謂的 托管服務(wù) 只需要實(shí)現(xiàn)框架中的 IHostedService 接口并囊括進(jìn)你需要的業(yè)務(wù)邏輯作為后臺(tái)任務(wù),這篇文章將會(huì)討論如何在 ASP.Net Core 中構(gòu)建托管服務(wù)。

        創(chuàng)建托管服務(wù)

        要想創(chuàng)建托管服務(wù),只需要實(shí)現(xiàn) IHostedService 接口即可,下面就是 IHostedService 接口的聲明。


        public?interface?IHostedService
        {
        ????Task?StartAsync(CancellationToken?cancellationToken);
        ????Task?StopAsync(CancellationToken?cancellationToken);
        }

        這一節(jié)中我們?cè)?ASP.Net Core 中做一個(gè)極簡(jiǎn)版的 托管服務(wù), 首先自定義一個(gè) MyFirstHostedService 托管類(lèi),代碼如下:


        ????public?class?MyFirstHostedService?:?IHostedService
        ????{
        ????????protected?async?override?Task?ExecuteAsync(CancellationToken?token)
        ????????{
        ????????????throw?new?NotImplementedException();
        ????????}
        ????}

        創(chuàng)建 BackgroundService

        有一點(diǎn)要注意,上一節(jié)的 MyFirstHostedService 實(shí)現(xiàn)了 IHostedService 接口,實(shí)際開(kāi)發(fā)中并不需要這樣做,因?yàn)?.Net Core 中已經(jīng)提供了抽象類(lèi) BackgroundService,所以接下來(lái)重寫(xiě)抽象類(lèi)的 ExecuteAsync 方法即可,如下代碼所示:


        ????public?class?MyFirstHostedService?:?BackgroundService
        ????{
        ????????protected?async?override?Task?ExecuteAsync(CancellationToken?token)
        ????????{
        ????????????throw?new?NotImplementedException();
        ????????}
        ????}

        下面的代碼片段展示了一個(gè)簡(jiǎn)單的 Log 方法,用于記錄當(dāng)前時(shí)間到文件中,這個(gè)方法由 托管服務(wù) 觸發(fā)。


        ????????private?async?Task?Log()
        ????????{
        ????????????using?(StreamWriter?sw?=?new?StreamWriter(@"D:\log.txt",true))
        ????????????{
        ????????????????await?sw.WriteLineAsync(DateTime.Now.ToLongTimeString());
        ????????????}
        ????????}

        使用 ExecuteAsync 方法

        接下來(lái)看看如何實(shí)現(xiàn) ExecuteAsync 方法,這個(gè)方法的邏輯就是周期性(second/s)的調(diào)用 Log() 方法,如下代碼所示:


        ????protected?async?override?Task?ExecuteAsync(CancellationToken?token)
        ????{
        ????????while?(!token.IsCancellationRequested)
        ????????{
        ????????????await?Log();
        ????????????await?Task.Delay(1000,?token);
        ????????}
        ????}

        好了,下面是完整的 MyFirstHostedService 類(lèi)代碼,僅供參考。


        using?Microsoft.Extensions.Hosting;
        using?System;
        using?System.IO;
        using?System.Threading;
        using?System.Threading.Tasks;
        namespace?HostedServicesApp
        {
        ????public?class?MyFirstHostedService?:?BackgroundService
        ????{
        ????????protected?async?override?Task?ExecuteAsync(CancellationToken?token)
        ????????{
        ????????????while?(!token.IsCancellationRequested)
        ????????????{
        ????????????????await?Log();
        ????????????????await?Task.Delay(1000,?token);
        ????????????}
        ????????}
        ????????private?async?Task?Log()
        ????????{
        ????????????using?(StreamWriter?sw?=?new?StreamWriter(@"D:\log.txt",true))
        ????????????{
        ????????????????await?sw.WriteLineAsync(DateTime.Now.ToLongTimeString());
        ????????????}
        ????????}
        ????}??
        }

        托管服務(wù)注冊(cè)

        托管服務(wù)類(lèi)已經(jīng)寫(xiě)好了,要想注入到 Asp.NET Core 中,需要在 Startup.ConfigureServices 中將 托管服務(wù)類(lèi) 注入到 ServiceCollection 中,如下代碼所示:


        ????public?void?ConfigureServices(IServiceCollection?services)
        ????{
        ????????services.AddHostedService();
        ????????services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        ????}?

        當(dāng)把應(yīng)用程序跑起來(lái)后,你會(huì)看見(jiàn)程序每秒都會(huì)往 ?D:\log.txt 文件中記錄日志。

        在 IHostedService 中提供的 StartAsyncStopAsync 可用于在 ASP.NET Core 中執(zhí)行或停止后臺(tái)任務(wù),你可以用它在你的應(yīng)用程序中更新數(shù)據(jù)或其他操作,還有這些周期性業(yè)務(wù)邏輯是跑在后臺(tái)線程中的,這樣就不會(huì)導(dǎo)致主請(qǐng)求線程的阻塞。

        譯文鏈接:https://www.infoworld.com/article/3390741/how-to-use-ihostedservice-in-aspnet-core.html


        瀏覽 74
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
          
          

            1. 国产免费专区 | 国产精品久久久婷婷五月 | 美女航空一级毛片免费 | 靠逼做爱| 自拍在线视频 |