首页 > 解决方案 > 无法从“方法组”转换为“TimerCallback”

问题描述

我正在尝试getOrg通过托管服务运行功能,但有些功能无法正常工作我不确定我做错了什么。

错误:

参数 1:无法从 'method group' 转换为 'TimerCallback' (CS1503)

public class TokenService : IHostedService
{
    public IConfiguration _Configuration { get; }
    protected IMemoryCache _cache;
    private Timer _timer;
    public IHttpClientFactory _clientFactory;

    private readonly IServiceScopeFactory _scopeFactory;

    public TokenService(IConfiguration configuration, IMemoryCache memoryCache, IHttpClientFactory clientFactory, IServiceScopeFactory scopeFactory)
    {
        _Configuration = configuration;
        _cache = memoryCache;
        _clientFactory = clientFactory;
        _scopeFactory = scopeFactory;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _timer = new Timer(getOrg, null, 0, 1000); // getting error here
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        //Timer does not have a stop. 
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    public async Task getOrg()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "organizations");
            var response = await _client_NP.SendAsync(request);
            var json = await response.Content.ReadAsStringAsync();
            OrganizationsClass.OrgsRootObject model = JsonConvert.DeserializeObject<OrganizationsClass.OrgsRootObject>(json);


            using (var scope = _scopeFactory.CreateScope())
            {
                var _DBcontext = scope.ServiceProvider.GetRequiredService<DBContext>();

                foreach (var item in model.resources)
                {
                    var g = Guid.Parse(item.guid);
                    var x = _DBcontext.Organizations.FirstOrDefault(o => o.OrgGuid == g);
                    if (x == null)
                    {
                        _DBcontext.Organizations.Add(new Organizations
                        {
                            OrgGuid = g,
                            Name = item.name,
                            CreatedAt = item.created_at,
                            UpdatedAt = item.updated_at,
                            Timestamp = DateTime.Now,
                            Foundation = 3
                        });
                    }
                    else if (x.UpdatedAt != item.updated_at)
                    {
                        x.CreatedAt = item.created_at;
                        x.UpdatedAt = item.updated_at;
                        x.Timestamp = DateTime.Now;
                    }
                }

                await getSpace();

                await _DBcontext.SaveChangesAsync();
            }
        }
}

标签: c#asp.net-core.net-core

解决方案


TimerCallback接受状态的对象参数。尝试更改getOrg为:

public async void getOrg(object state)

推荐阅读