为什么子域关闭程序中出现异常

本文关键字:异常 关闭程序 为什么 | 更新日期: 2023-09-27 18:12:47

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

如何防止程序关闭?

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();
    }
}
}

为什么子域关闭程序中出现异常

在。net 2.0(及以上版本)中,线程中未处理的异常会导致整个进程终止。

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