2
votes

I am not sure how to handle a following scenario. There is an interface that defines an event handling method 'OnSomethinHappening()'.

There is a base class that implements this as a virtual method and uses some async code in it.

There is a derived class that wants to override the virtual method, but also call the base.OnSomethingHappening().

 public interface ISomething
    {
        void OnSomethingHappening();
    }

    public class BaseClass
    {
        public virtual async void OnSomethingHappening()
        {
            await Task.Delay(1999);
        }
    }

    public class DerivedClass : BaseClass
    {
        public override void OnSomethingHappening()
        {
            base.OnSomethingHappening();
            //some more code
        }
    }

The problem is, I cannot mark the method invocation as awaitable, since it returns void. It is fine to have async void methods for event handlers, so it cannot be changed to a Task (it ain't my code either).

So, how should I make sure that my derived class executes the base.OnSomethingHappening() properly before going to own code?

Does this solution make sense in the derived class?:

public override async void OnSomethingHappening()
        {
           await Task.Run(()=> base.OnSomethingHappening());
            //some more code
        }
1
I also have the same issue. @Stephen Cleary can you help out? - Irshad

1 Answers

6
votes

So, how should I make sure that my derived class executes the base.OnSomethingHappening() properly before going to own code?

You don't. That's why async void methods should be avoided. They provide no possible way for the caller to know when the operation has completed, whether it completed successfully, or what the errors were, if there were any. If you want to be able to ensure that the caller is able to know that information about the method, it needs to return a Task, not void.