日期:2014-05-18  浏览次数:20974 次

c#中的多线程异常处理

1.对于Thread操作的异常处理

public static void Main()
{
  try
  {
    new Thread (Go).Start();
  }
  catch (Exception ex)
  {
    // We'll never get here!
    Console.WriteLine ("Exception!");
  }
}
static void Go() { throw null; }   // Throws a NullReferenceException


在go函数里抛出的异常时不会被主线程的try,catch捕捉的,各个线程应该有自己的try,catch去处理线程异常。

正确写法:

public static void Main()
{
   new Thread (Go).Start();
}
static void Go()
{
  try
  {
    ...
    throw null;    // The NullReferenceException will get caught below
    ...
  }
  catch (Exception ex)
  {
    Typically log the exception, and/or signal another thread
    that we've come unstuck
    ...
  }

}


2. 异步函数的异常处理

比如 WebClient中的 UploadStringAsync,它的异常会在UploadStringCompleted的参数error里

        static void Main(string[] args)
        {
            WebClient webClient = new WebClient();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler((sender, e) =>
                {
                    if (e.Error != null)
                    {
                        Console.WriteLine(e.Error.Message);


                    }
                });
            webClient.UploadStringAsync(new Uri("http://www.baidu.com"), "1111");
            Console.ReadKey();
        }


3 Task的异常处理