处理新流程中的异常

时间:2015-06-24 07:08:47

标签: .net process exception-handling

我在我的应用中运行了一个流程。有时第二个进程失败并抛出异常,但我无法在第一个进程中处理它们并且主应用程序崩溃,我该怎么做。

我按如下方式运行第二个流程:

try
{
Process proc = new Process();
...
proc.Start();
}
catch (Exception exp)
{
// never stops here even if proc fails
}

1 个答案:

答案 0 :(得分:1)

如果您想从流程执行切换到基于任务的执行,您可以尝试这些方法:

using System;
using System.Threading.Tasks;

namespace ExceptionsInTasks
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 4; i++)
            {                    
                try
                {
                    var t = Task.Factory.StartNew(() => DoWork(i));
                    t.Wait();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception occured in run {0}: {1}", i, ex.InnerException.Message);
                }
            }

            Console.ReadLine();
        }

        private static void DoWork(int i)
        {
            if (i % 2 == 0)
            {
                throw new System.Exception("Faulty execution");
            }
            else
            {
                Console.WriteLine("Successful execution in run " + i);
            }
        }
    }
}

这导致下面的输出。请注意,起始方法甚至通过InnerException属性提供有关实际异常的详细信息。

  • 在运行0中发生异常:执行错误
  • 在第1轮中成功执行
  • 第2次运行中发生异常:执行错误
  • 在第3轮中成功执行
相关问题