抛出异常时调用其他函数 - C#委托

时间:2011-05-03 11:13:12

标签: c#

如果委托指向5个方法,则在调用委托时,在第一个方法中发生重复。因为异常发生,所以无法调用4个函数中的其余函数。即使异常幸福,如何让委托调用其他函数

3 个答案:

答案 0 :(得分:5)

您需要使用Delegate.GetInvocationList基本上将委托拆分为单独的操作,并使用catch子句依次调用每个操作来处​​理异常。

例如:

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

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

当然,您可能只希望捕获特定类型的异常。

答案 1 :(得分:3)

您必须自己在try / catch块内调用(调用)订阅的处理程序。您可以使用GetInvocationList()获取列表。

更好的解决方案需要控制处理程序:它们不应该抛出。

处理例外的粗略代码:

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

答案 2 :(得分:1)

可能是以下代码将帮助您了解如何执行此操作。

 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
                {

                }
            }
        }
    }
}