为什么在子域关闭程序中例外?

时间:2011-10-28 22:18:54

标签: c# exception appdomain

为什么一个应用程序域中的异常会影响另一个应用程序域?

如何阻止关闭程序?

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 个答案:

答案 0 :(得分:0)

在.NET 2.0(及更高版本)中,线程中的未处理异常会导致整个进程终止。

您可以按照Hans的建议更改该策略,或者您只需使用try / catch包装代码并处理异常。