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

一个线程用于显示信息(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. Sharepoint2012 Report权限

    在主文件夹下,点击“文件夹设置”,如下图: 在打开的界面中,点击“新建角色分配”,如下图: 在打开的界面中,录入window组名,或是AD域账号,选择以下的角色,点击确定即可.

  2. Topcoder SRM583 DIV 2 250

    #include <string> #include <iostream> using namespace std; class SwappingDigits { public ...

  3. 省常中模拟 day1

    第一题: 题目大意: 给出N个数的数列,如果相邻的两个数加起来是偶数,那么就可以把这两个数消掉,求最多能消掉多少数. 解题过程: 1.先自己手工模拟了几组数据,发现不管消除的顺序如何,最终剩下的是一定 ...

  4. speechSynthesis

    /* $timeout.cancel(timer); */window.speechSynthesis.onvoiceschanged = function(e) { voices = speechS ...

  5. 去掉安卓中activity的标题栏

    去掉所有Activity界面的标题栏 修改AndroidManifest.xml 在application 标签中添加android:theme="@android:style/Theme. ...

  6. Ubuntu gmake: command not found

    由于ubuntu上取消了gmake(GUNmake)的而全部使用make代替.所以此问题的解决方式是有两种: 1.makefile中 gmake用make代替: 2.创建一个make的gmake连接: ...

  7. 深入理解gradle编译-Android基础篇

    深入理解gradle编译-Android基础篇 导读 Gradle基于Groovy的特定领域语言(DSL)编写的一种自动化建构工具,Groovy作为一种高级语言由Java代码实现,本文将对Gradle ...

  8. 【three.js详解之二】渲染器篇

    [three.js详解之二]渲染器篇   本篇文章将详细讲解three.js中渲染器(renderer)的设置方法. three.js文档中渲染器的分支如下: Renderers CanvasRend ...

  9. LINUX下如何开启FTP服务器

    1.首先应开启linuxh环境下的FTP service,过程如下:   http://www.witech.com.cn/news/Article_Show.asp?ArticleID=48    ...

  10. C++学习笔记24:makefile文件

    makefile make命令:负责c/c++程序编译与链接 make根据指定命令进行建构 建构规则文件:GNUmakefile , makefile,Makefile makefile 文件格式 m ...