2011-10-28 45 views
2

爲什麼在一個應用程序域中的異常會影響另一個應用程序域?爲什麼在子域關閉程序中異常?

如何防止程序關閉?

using System; 
using System.Reflection; 
using System.Threading; 

namespace domain 
{ 
public class Worker : MarshalByRefObject 
{ 
    public static void NotMyCodeThreadProc() 
    { 
     throw new Exception(); 
    } 

    public void NotMyCode() 
    { 
     var thread = new Thread(NotMyCodeThreadProc); 
     thread.Start(); 
     thread.Join(); 
    } 
} 

class Program 
{ 
    static void Main() 
    { 
     AppDomain ad = AppDomain.CreateDomain("New domain"); 
     Worker remoteWorker = (Worker) ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "domain.Worker"); 
     try 
     { 
      remoteWorker.NotMyCode(); 
     } 
     catch 
     { 
     } 
     Console.WriteLine("!"); 
     Console.ReadLine(); 
    } 
} 
} 
+1

您需要自定義CLR主機來更改未處理的異常策略。你不能用C#代碼編寫。 Google ICLRPolicyManager :: SetDefaultAction() –

回答

0

在.NET 2.0(及以上版本)中,線程中的未處理異常導致整個進程終止。

您可以按照Hans的建議更改該策略,也可以簡單地用try/catch包裝代碼並處理異常。

相關問題