本文主要介绍.NET Core(C#)中,编写简单没有后台service的示例代码,和有后台服务相关方法,以及示例代码。

1、编写简单的Console控制台程序

该程序将从命令行读取基本选项,然后在不进行用户交互的情况下执行和终止。

例如,

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace PackWidgetTemplate
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var host = CreateHostBuilder(args).Build())
            {
                await host.StartAsync();
                var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();
                // 写需要执行的代码
                lifetime.StopApplication();
                await host.WaitForShutdownAsync();
            }

        }
        private static IHostBuilder CreateHostBuilder(string[] args) =>
     Host.CreateDefaultBuilder(args)
         .UseConsoleLifetime()
         .ConfigureLogging(builder => builder.SetMinimumLevel(LogLevel.Warning))
         .ConfigureServices((hostContext, services) =>
         {
             services.Configure<MyServiceOptions>(hostContext.Configuration);
             services.AddHostedService<MyService>();
             services.AddSingleton(Console.Out);
         });
    }
}

2、编写一般Console控制台程序

Program.cs:

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace MyApp
{
    public static class Program
    {
        public static async Task Main(string[] args)
        {
            await CreateHostBuilder(args).RunConsoleAsync();
        }
        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseConsoleLifetime()
                .ConfigureLogging(builder => builder.SetMinimumLevel(LogLevel.Warning))
                .ConfigureServices((hostContext, services) =>
                {
                    services.Configure<MyServiceOptions>(hostContext.Configuration);
                    services.AddHostedService<MyService>();
                    services.AddSingleton(Console.Out);
                });
    }
}

MyServiceOptions.cs:

namespace MyApp
{
public class MyServiceOptions
{
public int OpCode { get; set; }
public int Operand { get; set; }
}
}

MyService.cs:

using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
namespace MyApp
{
    public class MyService : IHostedService
    {
        private readonly MyServiceOptions _options;
        private readonly TextWriter _outputWriter;
        public MyService(TextWriter outputWriter, IOptions<MyServiceOptions> options)
        {
            _options = options.Value;
            _outputWriter = outputWriter;
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _outputWriter.WriteLine("Starting work");
            DoOperation(_options.OpCode, _options.Operand);
            _outputWriter.WriteLine("Work complete");
        }
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            _outputWriter.WriteLine("StopAsync");
        }
        protected void DoOperation(int opCode, int operand)
        {
            _outputWriter.WriteLine("Doing {0} to {1}...", opCode, operand);
            // 执行可能耗时的代码
        }
    }
}

推荐文档