asp.net core定时任务保持存活,不会被回收。asp.net core回收事件

核心类,继承IHostedService,处理启动和退出方法


    public interface IHostedService
    {
		//启动程序时触发
        Task StartAsync(CancellationToken cancellationToken);

		//关闭时触发。IIS应用程序池回收时触发
        Task StopAsync(CancellationToken cancellationToken);
    }
    
   //注册启动类 
 services.AddHostedService<HostImpl>();
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using WebInfoFormReport.Model;

namespace WebInfoFormReport
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
         
            services.AddHostedService<HostImpl>();

            //services.AddRazorPages();
            services.AddMvcCore();

            HandleMq.ActiveWeb();
        }

    public class HostImpl : IHostedService
    {
        public static CancellationToken cancellationToken2 = new CancellationToken();

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            LogHelpter.AddLog("准备启动...");
            cancellationToken2 = new CancellationToken();

            HandleMq.MqMessageDo();

            var gg = Task.Run(() =>
             {
                 while (true)
                 {
                     Model.LogHelpter.AddLog("程序存活中..线程id=" + Thread.CurrentThread.ManagedThreadId);

                     HandleMq.ActiveWeb();

                     System.Threading.Thread.Sleep(8 * 1000);
                 }
             });

            await Task.CompletedTask;
            //throw new NotImplementedException();
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            try
            {
                //停止定时任务
                cancellationToken2.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog("停止定时任务出错," + ex.Message);
            }

            await Task.Run(() =>
            {
                LogHelpter.AddLog("程序正在被回收...");
                try
                {
                    //启动程序
                    Program.CreateHostBuilder(new string[] { }).Build().Run();
                }
                catch (Exception ex)
                {
                    Model.LogHelpter.AddLog("激活失败。" + ex.ToString());
                }
            });

        }
    }

    public class HandleMq
    {
        /// 
        /// 激活本系统
        /// 
        public static void ActiveWeb()
        {
            try
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.DownloadString("http://localhost:8043/");
                LogHelpter.AddLog("访问成功...");
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog("访问出错:" + ex.Message);
            }
        }

        /// 
        /// 处理MQ消息
        /// 
        public static void MqMessageDo()
        {
            HostImpl.cancellationToken2 = new CancellationToken();
            Task.Run(() =>
            {
                while (!HostImpl.cancellationToken2.IsCancellationRequested)
                {
                    LogHelpter.AddLog("处理MQ消息");
                    Thread.Sleep(10 * 1000);
                }
            });
        }

    }

}

你可能感兴趣的:(asp.net,core,c#,asp.net,core)