Pass async Callback to Timer constructor

前端 未结 2 1323
太阳男子
太阳男子 2021-02-05 01:27

I have async callback, which is passed into Timer(from System.Threading) constructor :

private async Task HandleTimerCallback(object state)
{
    if (timer == nu         


        
2条回答
  •  醉话见心
    2021-02-05 01:50

    You could use a wrapper method, as recommended by David Fowler here:

    public class Pinger
    {
        private readonly Timer _timer;
        private readonly HttpClient _client;
        
        public Pinger(HttpClient client)
        {
            _client = client;
            _timer = new Timer(Heartbeat, null, 1000, 1000);
        }
    
        public void Heartbeat(object state)
        {
            // Discard the result
            _ = DoAsyncPing();
        }
    
        private async Task DoAsyncPing()
        {
            await _client.GetAsync("http://mybackend/api/ping");
        }
    }
    

提交回复
热议问题