When to use callbacks instead of events in c#?

后端 未结 8 1679
春和景丽
春和景丽 2020-12-13 09:20

Forgive me if this a stupid question, I admit I haven\'t thought about it much.

But when would you favour using a callback (i.e, passing in a Func or Action), as oppo

8条回答
  •  误落风尘
    2020-12-13 09:49

    Generally, I use a callback if it is required, whereas an event is used when it should be optional. Don't expose an event if you're expecting there to always be something listening.

    Consider the following:

    public class MyClass_Event
    {
        public event EventHandler MakeMeDoWork;
    
        public void DoWork()
        {
            if (MakeMeDoWork == null)
                throw new Exception("Set the event MakeMeDoWork before calling this method.");
            MakeMeDoWork(this, EventArgs.Empty);
        }
    }
    

    versus:

    public class MyClass_Callback
    {
        public void DoWork(EventHandler callback)
        {
            if (callback == null)
                throw new ArgumentException("Set the callback.", "callback"); // better design
            callback(this, EventArgs.Empty);
        }
    }
    

    The code is almost the same as the callback can be passed as null, but at least the exception thrown can be more relevant.

提交回复
热议问题