Since there is no method transformed by PostSharp on the call stack when the exception is thrown, the aspect code does not execute at all. Getting the aspect to work on exactly this code without any direct changes is a bit tricky, but possible.
By default PostSharp's multicasting engine does not apply aspects to anonymous methods and other (VB or C#) compiler-generated code. While you can force PostSharp to apply on these methods, it's not recommended.
The other way is to target directly BackgroundWorker
and its DoWork
event. While you cannot directly change the implementation, you may intercept calls to event's methods from you code. Following is a simple implementation of such interception that wraps the incoming delegate so that it can be intercepted by your aspect (MyOnExceptionAspect
):
public class EventInterceptionProxy
{
private DoWorkEventHandler handler;
public EventInterceptionProxy(DoWorkEventHandler handler)
{
this.handler = handler;
}
[MyOnExceptionAspect]
public void Intercept(object sender, DoWorkEventArgs ea)
{
handler?.Invoke(sender, ea);
}
}
[Serializable]
public class AddHandlerInterception : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs args)
{
args.Arguments[0] =
new DoWorkEventHandler(new EventInterceptionProxy((DoWorkEventHandler) args.Arguments[0]).Intercept);
args.Proceed();
}
}
You can then apply the aspect using the following:
[assembly: AddHandlerInterception(
AttributeTargetTypes = "System.ComponentModel.BackgroundWorker",
AttributeTargetAssemblies = "System",
AttributeTargetMembers = "add_DoWork")]
All of the above code is just a demonstration. It does not handle handler removal and other side cases (usage in PCL libraries, thread safety, weak events...).