安全呼叫多播委託
曾經想要呼叫多播委託,但是你希望呼叫整個呼叫列表,即使鏈中的任何一個發生異常也是如此。那麼你很幸運,我已經建立了一個擴充套件方法來實現這一點,只有在執行整個列表完成後丟擲 AggregateException
:
public static class DelegateExtensions
{
public static void SafeInvoke(this Delegate del,params object[] args)
{
var exceptions = new List<Exception>();
foreach (var handler in del.GetInvocationList())
{
try
{
handler.Method.Invoke(handler.Target, args);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
if(exceptions.Any())
{
throw new AggregateException(exceptions);
}
}
}
public class Test
{
public delegate void SampleDelegate();
public void Run()
{
SampleDelegate delegateInstance = this.Target2;
delegateInstance += this.Target1;
try
{
delegateInstance.SafeInvoke();
}
catch(AggregateException ex)
{
// Do any exception handling here
}
}
private void Target1()
{
Console.WriteLine("Target 1 executed");
}
private void Target2()
{
Console.WriteLine("Target 2 executed");
throw new Exception();
}
}
這輸出:
Target 2 executed
Target 1 executed
直接呼叫,沒有 SaveInvoke
,只會執行目標 2。