简体   繁体   中英

calling the other functions when an exception is thrown - C# delegates

if a delegate points to 5 methods, when delegate is invoked an excpetion happens in first method. since the exception happens the rest of the 4 functions cannot be called. How to make the delegate to call other functions even when exceptions happpens

You'd need to use Delegate.GetInvocationList to basically split the delegate into the individual actions, and call each in turn with a catch clause to handle the exceptions.

For example:

Action[] individualActions = (Action[]) multicast.GetInvocationList();

foreach (Action action in individualActions)
{
    try
    {
        action();
    }
    catch (Exception e)
    {
        // Log or whatever
    }
}

You may want to only catch specific types of exception, of course.

You will have to call (Invoke) the subscribed handlers yourself, inside a try/catch block. You can get the list with GetInvocationList() .

The better solution requires control over the handlers: They should not throw.

The rough code for handling the exceptions:

        foreach (Delegate handler in myDelegate.GetInvocationList())
        {
            try
            {
                object params = ...;
                handler.Method.Invoke(handler.Target, params);
            }
            catch(Exception ex)
            {
                // use ex
            }
        }

May be following code will help you understand how to do that.

 public class DynamicInvocation
{
    public event EventHandler SomeEvent;
    public void DoWork()
    {
        //Do your actual code here
        //...
        //...
        //fire event here
        FireEvent();
    }

    private void FireEvent()
    {
        var cache = SomeEvent;
        if(cache!=null)
        {
            Delegate[] invocationList = cache.GetInvocationList();
            foreach (Delegate @delegate in invocationList)
            {
                try
                {
                    @delegate.DynamicInvoke(null);
                }
                catch
                {

                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM