![](/img/trans.png)
[英]AppDomain.AssemblyLoad event catches all exceptions raised within the event handlers
[英]Throw exception from AppDomain.AssemblyLoad event
有人可以向我解釋為什么我似乎無法從AppDomain.Assembly加載事件中拋出異常? 例如:
class Program
{
static Program()
{
AppDomain.CurrentDomain.UnhandledException += (s, a) =>
{
Console.WriteLine("Caught exception!");
};
AppDomain.CurrentDomain.AssemblyLoad += (s, a) =>
{
Console.WriteLine(string.Format("Assembly {0} loaded", a.LoadedAssembly.FullName));
throw new Exception();
Console.WriteLine("Should never get here...");
};
}
static void Main(string[] args)
{
Console.WriteLine(new ClassLibrary1.Class1().TestString());
Console.WriteLine();
Console.WriteLine("Done...");
Console.ReadLine();
}
}
執行此操作時,輸出如下:
Assembly ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null loaded
TestString
Done...
任何人都可以向我解釋這種行為嗎? 謝謝。
編輯澄清一些事情:
當我希望它運行時,程序集加載事件運行正常。 但我的異常永遠不會被拋出
這是一個從更大的應用程序中提取的蒸餾示例。 我想在裝載后檢查裝配,如果我不喜歡它,我想快速失敗......但是我的例外不會“發生”
這是因為JIT編譯器的工作方式。 它需要在Main()方法開始運行之前生成代碼。 由於您引用了ClassLibrary1.Class1()類型,因此需要加載該程序集以檢索類型信息。 這需要它在代碼開始運行之前加載程序集。 像這樣更改以獲得異常:
using System.Runtime.CompilerServices;
...
static void Main(string[] args) {
Test();
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void Test() {
Console.WriteLine(new ClassLibrary1.Class1().TestString());
Console.WriteLine();
Console.WriteLine("Done...");
Console.ReadLine();
}
現在,靜態構造函數可以先運行,並在加載ClassLibrary1程序集之前注冊AssemblyLoad事件處理程序。
拋出異常。 但似乎.Net有時會忽略啟動時發生的異常(Main())。 我不確定原因,但我通常會進入Debug-> Exceptions並選中“拋出公共語言運行時異常”框,以便能夠在異常處中斷。
為什么你認為異常沒有被拋出? 如果它沒有被拋出,人們會期望看到你的“永遠不會到達......”輸出。 但是,由於它不存在,所以可能會拋出異常。
您的代碼沒有捕獲異常是另一個故事。 提升AppDomain.AssemblyLoad事件的代碼很可能是捕獲異常。
我相信程序集加載事件發生在一個單獨的線程上,使用asynccallback。 您沒有得到異常,因為您需要使用Application.ThreadException + = new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
我想,我根本就不是這方面的專家
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.