通用主机的示例

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using Microsoft.Extensions.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Utils.HttpManager.Extension;

namespace ConsoleAppNet6 // Note: actual namespace depends on the project name.
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("server:0 stop 1 init; 2 start ");
            IHostBuilder builder = null;
            var tokenSource = new CancellationTokenSource();
            bool isInit = false;
            while (true)
            {
                
                var key = Console.ReadKey();
                
               
                Task<IHost> hostTaskInfo = null;
                if (key.Key == ConsoleKey.NumPad1 && (!isInit))
                {
                    isInit = true;
                    builder = CreateHostBuilder(args);
                }
                else if (key.Key == ConsoleKey.NumPad2 && isInit)
                {
                    
                   hostTaskInfo = builder.StartAsync(tokenSource.Token);
                    
                }
                else if (key.Key == ConsoleKey.NumPad0 && isInit)
                {
                    tokenSource.Cancel();
                    
                    break;
                }
                else
                {
                    Console.WriteLine("\nerror key! 0 stop 1 init; 2 start");
                }
            }

            Console.ReadLine();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                
                //services.AddHttpClient();
                services.AddHostedService<MyWorkerService>();
            });
        
    }

    public class MyWorkerService : IHostedService
    {
        private HttpClient _httpClient;
        private IHttpClientFactory _httpClientFactory;
        public MyWorkerService(IHostApplicationLifetime appLifetime,IHttpClientFactory fac)
        {
            appLifetime.ApplicationStarted.Register(StartEnd);
           
            _httpClient = fac.CreateClient();
            _httpClientFactory = fac;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                Console.WriteLine("1. do Work");
                await Task.Delay(1000 * 5);
                
            }
            
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            

            return Task.CompletedTask;
        }

        private void StartEnd()
        {
            
        }

      
    }
}

  

posted on 2022-02-12 14:54  SZMD.ls.nct  阅读(27)  评论(0)    收藏  举报

导航