开发者

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 res开发者_如何学JAVAt 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
                {

                }
            }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜