how to await an event handler invocation?

后端 未结 3 1002
迷失自我
迷失自我 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-22 02:31

    You could declare the Success property as Task instead of bool. Then assign it inside the handler like this:

    private void SomeEventHandler(object sender, MyEventArgs e)
    {
        e.Success = AnAsyncMethod(); // Without await
    }
    

    At the end you would be able to get the result after invoking the event and awaiting the property.

    public virtual async Task TrySomething()
    {
        var args = new MyEventArgs();
        SomeEvent?.Invoke(this, args);
        return await (args.Success ?? Task.FromResult(false));
    }
    

提交回复
热议问题