【发布时间】:2011-03-29 19:47:08
【问题描述】:
我正在开展一个将启动多个独立流程的项目。我希望它们被隔离到一个点,即如果一个意外失败,其他人将继续运行而不会受到影响。我尝试了一个 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);
}
}
}
}
编辑
请注意,“测试”类非常简化。实际的实现将非常复杂,并且在异常处理方面很可能存在差距。
【问题讨论】:
标签: c# .net multithreading