One shot events using Lambda in C#

前端 未结 8 1626
無奈伤痛
無奈伤痛 2021-01-31 07:55

I find myself doing this sort of thing quite often:-

 EventHandler eh = null;  //can\'t assign lambda directly since it uses eh
 eh = (s, args) =>
 {
     //s         


        
相关标签:
8条回答
  • 2021-01-31 08:27

    You probably want to work with the new async/await idioms. Usually when I need to execute an event handler one-shot like you described, what I really need is something like:

    await variableOfSomeSort.SomeMethodAsync();
    //small snippet of code here
    
    0 讨论(0)
  • 2021-01-31 08:28

    Does it work? If so, then I say go for it. For a one-shot event that looks to be quite elegant.

    What I like...

    • If s is garbage collected, so will the event handler.
    • The detaching code is right next to the attaching code, making it easy to see what you are are doing.

    You might be able to generalize it, but I'm not entierly sure how to because I can't seem to get a pointer to a event.

    0 讨论(0)
提交回复
热议问题