为什么子域关闭程序异常?

发布于 2024-12-13 01:24:04 字数 842 浏览 2 评论 0原文

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

如何防止程序关闭?

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

Why exception in one application domain affect another application domain?

How do I prevent the closing of the program?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋千易 2024-12-20 01:24:04

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

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

In .NET 2.0 (and above), an unhandled exception in a thread causes the entire process to terminate.

You can change that policy by following Hans' advice, or you can simply wrap your code with try/catch and handle the exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文