C# 如何在ASP.Net核心中使用IHostedService?

C# 如何在ASP.Net核心中使用IHostedService?,c#,api,asynchronous,asp.net-core,C#,Api,Asynchronous,Asp.net Core,我有一个调用RESTAPI的类。API每隔几分钟返回一次新数据。我想使用托管服务执行后台任务,以便每5分钟调用一次API。我的代码是不是应该是什么?这与后台服务有什么不同 public class APICaller : IHostedService { private Timer _timer; public Task StartAsync(CancellationToken stoppingToken) { _timer = new Timer(ca

我有一个调用RESTAPI的类。API每隔几分钟返回一次新数据。我想使用托管服务执行后台任务,以便每5分钟调用一次API。我的代码是不是应该是什么?这与后台服务有什么不同

public class APICaller : IHostedService
{
    private Timer _timer;

    public Task StartAsync(CancellationToken stoppingToken)
    {
        _timer = new Timer(call, null, 0, 300000); //Every 5 minutes

        return Task.CompletedTask;
    }

    private void call(object state)
    {
        var client = new RestClient("https://api.example.com/values/d=A");
        var request = new RestRequest(Method.GET);
        request.AddHeader("accept", "application/json; charset=utf-8");
        IRestResponse response = client.Execute(request);
        var responseContent = response.Content;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }
}

你的代码看起来不错。尽管我认为你最好还是打电话而不是
\u timer?.Change(Timeout.Infinite,0)
。但最终,这可能无关紧要,因为这只在应用程序停止时运行

这里介绍了
BackgroundService
的实现,以及如何使用它的示例:

BackgroundService
类继承自
IHostedService
。它只是更改了您的实现,因此您只需要实现
ExecuteAsync()
,而不是
StartAsync()
StopAsync()
。它只是让你的代码简单一点,有点