Skip to main content
 首页 » 编程设计

c#之多线程未处理的异常

2024年02月23日14youxin

我正在从事一个将启动多个独立流程的项目。我希望他们被隔离到这样一个地步,如果一个意外失败,其他人将继续而不会受到影响。我尝试了一个 POC(粘贴在下面)来使用 AppDomains 对此进行测试,但它仍然会使整个父应用程序崩溃。

我是不是采取了错误的方法?如果是这样,我应该做什么?如果不是,我做错了什么?

class Program 
{ 
    static void Main(string[] args) 
    { 
        Random rand = new Random(); 
        Thread[] threads = new Thread[15]; 
        for (int i = 0; i < 15; i++) 
        { 
            AppDomain domain = AppDomain.CreateDomain("Test" + i); 
            domain.UnhandledException += new UnhandledExceptionEventHandler(domain_UnhandledException); 
            domain. 
            Test test = domain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, "ConsoleApplication1.Test") as Test; 
            Thread thread = new Thread(new ParameterizedThreadStart(test.DoSomeStuff)); 
            thread.Start(rand.Next()); 
            Console.WriteLine(String.Format("Thread #{0} has started", i)); 
            threads[i] = thread; 
        } 
 
        for (int i = 0; i < 15; i++) 
        { 
            threads[i].Join(); 
            Console.WriteLine(String.Format("Thread #{0} has finished", i)); 
        } 
        Console.ReadLine(); 
    } 
 
    static void domain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
    { 
        Console.WriteLine("UNHANDLED"); 
    } 
 
 
} 
 
public class Test : MarshalByRefObject 
{ 
    public void DoSomeStuff(object state) 
    { 
        int loops = (int)state; 
        for (int i = 0; i < loops; i++) 
        { 
            if (i % 300 == 0) 
            { 
                // WILL break 
                Console.WriteLine("Breaking"); 
                int val = i / (i % 300); 
            } 
        } 
    } 
} 

编辑

请注意“测试”类非常简单。实际实现将极其复杂,并且很可能在异常处理方面存在差距。

请您参考如下方法:

您不需要单独的 AppDomain。您需要做的就是在 Test 类的 DoSomeStuff 成员中捕获异常。因此,如果其中一个线程处理了自己的异常,那么您的应用程序的其余部分可以继续运行。