【问题标题】:Make a thread to execute certain code every X seconds, in ASP.NET Web API在 ASP.NET Web API 中创建一个线程每 X 秒执行一次特定代码
【发布时间】:2021-10-03 10:31:11
【问题描述】:

我需要在我的 C# Net Core WebApi 的单独线程中执行某些调用。我一直在查看一些文档,但没有找到任何可以满足我需求的文档。

我有这个代码作为我的Program.cs(用于测试海豚),但我不工作:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;

namespace backend
{
    public class Program
    {
       
        public static void Main(string[] args)
        {
            Timer timer = new Timer(1000);
            timer.AutoReset = true;
            timer.Elapsed += new ElapsedEventHandler(test);
            timer.Start();
            CreateHostBuilder(args).Build().Run();
            
        }
        public static void test(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Look mom, I'm on a thread.");

        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

我对这个话题有点陌生。任何提示或想法?

【问题讨论】:

标签: c# multithreading asp.net-web-api .net-core


【解决方案1】:

我已经解决了这个documentation。我创建了一个后台服务并从 Startup.cs 添加到服务中。

文档:

Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            /*...*/
            services.AddHostedService<TimedBackgroundService>();
            /*...*/
        }

程序.cs

namespace backend
{
    public class Program
    {
       
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
            
        }
        

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

TimedBackgroundService.cs

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace backend
{
    public class TimedBackgroundService:IHostedService, IDisposable
    {
        private int executionCount = 0;
        private readonly ILogger<TimedBackgroundService> _logger;
        private Timer _timer;
        public TimedBackgroundService(ILogger<TimedBackgroundService> logger)
        {
            _logger = logger;
        }

        public Task StartAsync(CancellationToken stoppingToken)
        {

            _logger.LogInformation("Timed Hosted Service running.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(5));

            return Task.CompletedTask;
        }
        private void DoWork(object state)
        {
            Console.WriteLine("I'm working on a background Service");
        }
        public void Dispose()
        {
            _timer?.Dispose();
        }
        public Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Timed Hosted Service is stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }
    }
}

【讨论】:

  • 你也可以扩展BackgroundService然后执行while(true){ await Task.Delay(...); DoWork(); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多