Pass async Callback to Timer constructor

前端 未结 2 1327
太阳男子
太阳男子 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");
        }
    }
    
    0 讨论(0)
  • 2021-02-05 01:57

    Is there any way to omit that o param in lambda?

    Sure, just define your event handler method as async void:

    private async void HandleTimerCallback(object state)
    
    0 讨论(0)
提交回复
热议问题