多线程编程中要注意对线程异常的处理。首先写个例子。

一个线程用于显示信息(Show Messages)。主线程用于做其他工作(Do Works)。

            using (Task taskShowMessages = new Task(ShowMessages))
{
try
{
taskShowMessages.Start();
DoWorks();
}
catch (DoWorkException ex)
{
Console.WriteLine("Error:{0}", ex.Message);
}
catch(Exception ex)
{
Console.WriteLine("Error:{0}", ex.Message);
}
}
 public static void ShowMessages()
{
int i = ;
while (true)
{
Console.WriteLine("{0} - Message_{1}", DateTime.Now.ToString(), i++);
Thread.Sleep(); if ( i == 3)
{
throw new ShowMessageException(string.Format("User defined error occured during showing message_{0}!", i));
//throw new Exception(string.Format("Unhandled exception occured during showing message_{0}!", i));
}
}
} public static void DoWorks()
{
int i = ;
while (true)
{
Console.WriteLine("{0} - DoWork_{1}", DateTime.Now.ToString(), i++);
Thread.Sleep(); if (i == )
{
throw new DoWorkException(string.Format("User defined error occured during doing work_{0}!", i));
//throw new Exception(string.Format("Unhandled exception occured during doing work{0}!", i));
}
}
} public class ShowMessageException : Exception
{
public ShowMessageException(String message)
: base(message)
{
}
} public class DoWorkException : Exception
{
public DoWorkException(String message)
: base(message)
{
}
}

输出:

// :: PM - DoWork_0
// :: PM - Message_0
// :: PM - Message_1
// :: PM - DoWork_1
// :: PM - Message_2
// :: PM - DoWork_2
// :: PM - DoWork_3
Error:User defined error occured during doing work_4!

可以看出来,Show Message 3 时发生一个异常,但是本程序无视它并继续DoWorks。知道DoWorks发生异常抛出。
在VS的debug环境下可以看到这个异常的发生:

A first chance exception of type 'ConsoleApplication2.Program.ShowMessageException' occurred in ConsoleApplication2.exe
A first chance exception of type 'ConsoleApplication2.Program.DoWorkException' occurred in ConsoleApplication2.exe

如果想正确的处理ShowMessage线程的异常,必须对其 Wait()方法进行处理。

            using (Task taskShowMessages = new Task(ShowMessages))
{
try
{
taskShowMessages.Start();
DoWorks();
}
catch (DoWorkException ex)
{
Console.WriteLine("Error is handled:{0}", ex.Message);
}
finally
{
try
{
taskShowMessages.Wait();
}
catch(AggregateException ae)
{
ae.Handle((x) =>
{
if (x is ShowMessageException)
{
Console.WriteLine("Error is handled:{0}", x.Message);
return true;
}
else
{
return false;
}
});
}
}
}

输出:

// :: PM - DoWork_0
// :: PM - Message_0
// :: PM - Message_1
// :: PM - DoWork_1
// :: PM - Message_2
// :: PM - DoWork_2
// :: PM - DoWork_3
Error is handled:User defined error occured during doing work_4!
Error is handled:User defined error occured during showing message_3!

那么现在如果其中一个线程出现异常的话,我们就希望抛出异常,结束程序,怎么做?

答案就是使用:

CancellationTokenSource

        static CancellationTokenSource cancellationtoken = new CancellationTokenSource();
static void Main(string[] args)
{ using (Task taskShowMessages = new Task(ShowMessages, cancellationtoken.Token))
{
try
{
taskShowMessages.Start();
DoWorks();
}
catch (DoWorkException ex)
{
Console.WriteLine("Error is handled:{0}", ex.Message);
}
finally
{
cancellationtoken.Cancel(); try
{
taskShowMessages.Wait();
}
catch (AggregateException ae)
{
ae.Handle((x) =>
{
if (x is ShowMessageException)
{
Console.WriteLine("Error is handled:{0}", x.Message);
return true;
}
else
{
return false;
}
});
}
}
}
} public static void ShowMessages()
{
int i = ;
while (!cancellationtoken.IsCancellationRequested)
{
Console.WriteLine("{0} - Message_{1}", DateTime.Now.ToString(), i++);
Thread.Sleep(); if ( i == )
{
//throw new ShowMessageException(string.Format("User defined error occured during showing message_{0}!", i));
//throw new Exception(string.Format("Unhandled exception occured during showing message_{0}!", i));
//break;
}
}
}

输出:

// :: PM - DoWork_0
// :: PM - Message_0
// :: PM - Message_1
// :: PM - DoWork_1
// :: PM - Message_2
// :: PM - Message_3
// :: PM - DoWork_2
// :: PM - Message_4
// :: PM - Message_5
// :: PM - DoWork_3
// :: PM - Message_6
// :: PM - Message_7
Error is handled:User defined error occured during doing work_4!

参考:

https://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/dd537614(v=vs.110).aspx

(C#) Tasks 中的异常处理(Exception Handling.)的更多相关文章

  1. Akka(26): Stream:异常处理-Exception handling

    akka-stream是基于Actor模式的,所以也继承了Actor模式的“坚韧性(resilient)”特点,在任何异常情况下都有某种整体统一的异常处理策略和具体实施方式.在akka-stream的 ...

  2. Exception Handling Considered Harmful

    异常处理被认为存在缺陷 Do, or do not. There is no try. - Yoda, The Empire Strikes Back (George Lucas) by Jason ...

  3. C#编程.异常处理(Exception Handling Statements)

    C#语言包含结构化异常处理(Structured Exception Handling,SEH). throw The throw statement is used to signal the oc ...

  4. 异常处理与MiniDump详解(3) SEH(Structured Exception Handling)

    write by 九天雁翎(JTianLing) -- blog.csdn.net/vagrxie 讨论新闻组及文件 一.   综述 SEH--Structured Exception Handlin ...

  5. Exception handling 异常处理的本质

    异常处理的本质:状态回滚或者状态维护. https://en.wikipedia.org/wiki/Exception_handling In general, an exception breaks ...

  6. Exception Handling in ASP.NET Web API webapi异常处理

    原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...

  7. C# to IL 10 Exception Handling(异常处理)

    Exception handling in IL is a big let down. We expected a significant amount of complexity,but were ...

  8. Exception Handling引入MVP

    异常处理(Exception Handling)是所有系统的最基本的基础操作之一,其它的比如日志(Logging).审核(Auditing).缓存(Caching).事务处理(Transaction) ...

  9. Unity、Exception Handling引入MVP

    什么是MVP?在“MVP初探”里就有讲过了,就是一种UI的架构模式. 简单的描述一下Unity和Exception Handling Application Block: Unity是一个轻量级的可扩 ...

随机推荐

  1. iOS应用之间跳转

    本篇博文将涉及到以下知识点: app应用跳转的原理解析 如何实现两个app应用之间的跳转 如何实现两个app之间跳转到指定界面 二.应用跳转原理 相信从一个应用跳转到另一个应用大家并不陌生,最常见的莫 ...

  2. 困扰我多年的Connection reset问题

    第一次出现:是thrift的python client去请求server,发现偶尔出现这个问题 第二次:接入第三方的api,去请求数据时,发现一个接入方的api第一次总是报这个错,当时又没有做处理,导 ...

  3. 使用urllib编写python爬虫

    新版python中,urllib和urllib2合并了,统一为urllib (1)简单爬取网页 import urllib content = urllib.request.urlopen(req). ...

  4. Java类的成员函数调用顺序

    class A { public A() { System.out.println("----------A 构造-------------"); } static void sb ...

  5. c#新手之1-如何组织类及相互调用

    不知道这个文章的名字起的对不对,姑且这么叫吧.我在这之前用c语言写程序几乎很少用函数调用来解决问题,都是用全局变量然后面向过程对数据做简单的处理,这就造成了我在学习c@之后仍有这个毛病,好点的时候有个 ...

  6. R on Ubuntu

    I have been using R recently. R is statistics programming language. R has attracted more and more at ...

  7. SharePoint 2016 Beta 2 安装体验

    博客地址:http://blog.csdn.net/FoxDave 最近忙碌了一段时间,2016正式版快要发布了,想尽快熟悉熟悉.2016不再提供免费版Foundation的支持,只有Server版本 ...

  8. Genymotion--最快的安卓模拟器 测试与模拟APP应用必备

    命令行工具,Eclipse插件,多操作系统 1 易于安装,易于运行 超过10个虚拟设备 您很匆忙?您想测试市场的主要设备?使用我们的虚拟设备! 2 控制功能强大的传感器来测试您的应用程序 自定义你的测 ...

  9. Asp.net useful tools

    fuslogvw trace the assembly binding when app start up. ILdasm to inspect the manifest of the assembl ...

  10. 传智播客JavaWeb day06-jstl

    一.jsp标签(sun公司提供的) 二.EL表达式 三.jstl (javaserver pages standard tag library) 1.为什么要有jstl jsp标签太弱,el表达式功能 ...