[英]Handling exception in c# backgroundWorker
我評估Postsharp以便在應用程序中進行部署。 我想用postharp處理應用程序中所有未捕獲的異常。這樣,我在OnExceptionAspect的子類中實現了OnException方法。 在我的測試中,所有異常都被捕獲,除了一種情況下的一種異常:當將異常拋出到backgroundWorker中時。
我的課 :
public class Test {
public void MethodTest() {
//...
// if I throw an exception here, no problem : postsharp aspect intercept
// below, postsharp don't intercept the exception :
BackgroundWorker bgw = new BackgroundWorker() ;
bgw.DoWork += (object sender2, DoWorkEventArgs e2) => {
//...
throw new NotImplementedException();
}
bgw.RunWorkerAsync();
}
}
您能否建議攔截此異常?
謝謝您的幫助。
由於拋出異常時調用堆棧上沒有PostSharp轉換的方法,因此方面代碼根本不會執行。 在不進行任何直接更改的情況下,使方面能夠完全在此代碼上工作是有些棘手的,但是可能的。
默認情況下,PostSharp的多播引擎不會將方面應用於匿名方法和其他(VB或C#)編譯器生成的代碼。 雖然可以強制PostSharp應用於這些方法,但不建議這樣做。
另一種方法是直接定位BackgroundWorker
及其DoWork
事件。 雖然您不能直接更改實現,但可以從代碼中攔截對事件方法的調用。 以下是這種截取的簡單實現,它包裝了傳入的委托,以便您的方面( 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();
}
}
然后,您可以使用以下方法應用方面:
[assembly: AddHandlerInterception(
AttributeTargetTypes = "System.ComponentModel.BackgroundWorker",
AttributeTargetAssemblies = "System",
AttributeTargetMembers = "add_DoWork")]
以上所有代碼僅是一個演示。 它不處理處理程序刪除和其他附帶情況(在PCL庫中使用,線程安全,弱事件...)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.