作者:liutiancinet | 来源:互联网 | 2024-10-12 14:47
usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Hosting;usingSyste
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 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();
});
}
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()
{
}
}
}