how to await an event handler invocation?

后端 未结 3 1004
迷失自我
迷失自我 2020-12-22 02:06

basically, i have a method which invokes an event handler. the event handler calls an async method and i need to know the results of that method (true or false). since event

3条回答
  •  梦毁少年i
    2020-12-22 02:52

    The whole reason async void is allowed is for event handlers. From the documentation on Async Return Types:

    You use the void return type in asynchronous event handlers, which require a void return type.

    That said, events are designed to "signal the occurrence of an action" to any interested party, if any (and there can be none, or multiple). Think of it like sending an email notification to whomever subscribed to a specific mailing list: those people might have to do something when they receive the notification, but it's not your concern - you move on to your next task after sending the email. That's all events are. An event handler should not be something that is important for the proper functioning of the object.

    Events are not designed to be a "hey this happened, what should I do next?" So there should be no need to await an event handler.

    If returning args.Success depends on SomeEventHandler completing successfully, then it shouldn't be an event handler. Instead, you can have a Func> property (a function that returns Task). Something like this:

    public class SomeClass {
        private Func> IsSuccessful;
    
        public SomeClass(Func> isSuccessful) {
            // Accept a reference to a function and store it
            IsSuccessful = isSuccessful;
        }
    
        public async Task DoSomething() {
            // Call our function and return the result
            return await IsSuccessful();
        }
    }
    

    Then you could use it like this:

    // This is the method we want it to call
    private async Task AnAsyncMethod() {
      await Task.Delay(1);
      return true;
    }
    
    // so we pass it in the constructor of the class.
    // You don't have to pass it in the constructor - this is just an example
    var myClass = new SomeClass(AnAsyncMethod);
    

    In that way, it's very clear that SomeClass cannot function properly without calling that method and therefore exactly one implementation of that method must be passed into the class.

提交回复
热议问题