Please explain Timer event async/await syntax

后端 未结 3 2136
时光取名叫无心
时光取名叫无心 2020-12-18 09:04

I researched the asynch and await syntax here and here. It really helps to understand the usage but I found an intriguing syntax example on MSDN which I just don\'t understa

相关标签:
3条回答
  • 2020-12-18 09:29

    It assigns an async lambda to the Elapsed event of timer. You can understand the async lambda this way: first, the following is a lambda:

    (sender, e) => HandleTimer()
    

    this lambda calls HandleTimer synchronously. Then we add an await to call HandleTimer asynchronously:

    (sender, e) => await HandleTimer()
    

    but this won't work because to call something asynchronously you have to be asynchronous yourself, hence the async keyword:

    async (sender, e) => await HandleTimer()
    
    0 讨论(0)
  • 2020-12-18 09:29

    The code you've given is an anonymous function written as a lambda expression.

    So what's really happening is that for the timer elapsed event you're assigning the EventHandler as async ( sender, e ) => await HandleTimer();.

    which translates to something like

    timer.Elapsed += AnonFunc;
    
    async void AnonFunc(object sender, EventArgs e)
    {
        await HandleTImer();
    }
    

    It seems that it's the lambda that's tripping you up.

    0 讨论(0)
  • 2020-12-18 09:31

    This is just an asynchronous lambda expression. It's equivalent to:

    timer.Elapsed = CallHandleTimer;
    
    async void CallHandleTimer(object sender, EventArgs e)
    {
        await HandleTimer();
    }
    
    0 讨论(0)
提交回复
热议问题