(C#) Tasks 中的异常处理(Exception Handling.)
多线程编程中要注意对线程异常的处理。首先写个例子。
一个线程用于显示信息(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.)的更多相关文章
- Akka(26): Stream:异常处理-Exception handling
akka-stream是基于Actor模式的,所以也继承了Actor模式的“坚韧性(resilient)”特点,在任何异常情况下都有某种整体统一的异常处理策略和具体实施方式.在akka-stream的 ...
- Exception Handling Considered Harmful
异常处理被认为存在缺陷 Do, or do not. There is no try. - Yoda, The Empire Strikes Back (George Lucas) by Jason ...
- C#编程.异常处理(Exception Handling Statements)
C#语言包含结构化异常处理(Structured Exception Handling,SEH). throw The throw statement is used to signal the oc ...
- 异常处理与MiniDump详解(3) SEH(Structured Exception Handling)
write by 九天雁翎(JTianLing) -- blog.csdn.net/vagrxie 讨论新闻组及文件 一. 综述 SEH--Structured Exception Handlin ...
- Exception handling 异常处理的本质
异常处理的本质:状态回滚或者状态维护. https://en.wikipedia.org/wiki/Exception_handling In general, an exception breaks ...
- Exception Handling in ASP.NET Web API webapi异常处理
原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...
- C# to IL 10 Exception Handling(异常处理)
Exception handling in IL is a big let down. We expected a significant amount of complexity,but were ...
- Exception Handling引入MVP
异常处理(Exception Handling)是所有系统的最基本的基础操作之一,其它的比如日志(Logging).审核(Auditing).缓存(Caching).事务处理(Transaction) ...
- Unity、Exception Handling引入MVP
什么是MVP?在“MVP初探”里就有讲过了,就是一种UI的架构模式. 简单的描述一下Unity和Exception Handling Application Block: Unity是一个轻量级的可扩 ...
随机推荐
- 读javascript高级程序设计14-错误处理与调试
一 错误类型 ECMA规定了常见的7种错误类型: Error: 基类型.其他常见的错误类型都继承自该类型,一般供开发人员抛出自定义错误. EvalError:该类型会在eval()函数使用异常时被抛 ...
- C#中combobox不可编辑与不可选择
不可编辑:comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; 将Style属性改为csDropDownL ...
- NET中的规范标准注释(二) -- 创建帮助文档入门篇
一.摘要 在本系列的第一篇文章介绍了.NET中XML注释的用途, 本篇文章将讲解如何使用XML注释生成与MSDN一样的帮助文件.主要介绍NDoc的继承者:SandCastle. 二.背景 要生成帮助文 ...
- CSS3制作漂亮的照片墙
CSS3可以做动画大家肯定都是耳熟能详的了,但是大家有木有巧妙的利用这一个功能来制作一款漂亮的照片墙呢? 那么今天我们就利用CSS3动画这一特性来一起制作漂亮的照片墙吧! 第一部分:HTML 这里我们 ...
- 跟大牛之间关于hibernate的一些探讨记录
hibernate的工作原理!! 1.读取配置文件 2.读取并解析映射信息,创建SessionFactory 3.打开Session 4.创建事务Transcation 5.持久化操作 6.提交事务 ...
- C# 代码示例_结构/数组/枚举...
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- Python 基礎 - if else流程判斷
hmm~前面講了那麼多,終於可以稍稍的正式進入另一個階段,沒錯,要開始寫判斷式了 這次先從最簡單的判斷式開始,if else 開始- Go 首先,之前有寫有一個簡單的互動式 用戶輸入 的代碼,忘記了嗎 ...
- oracle数据库解析json格式
随着非关系型数据大规模使用,以json格式产生的数据也出现在我所管理的Oracle数据库的CLOB字段里面,使用过程中就需要解析出指定键的值. 使用了最新版本 如果Oracle版本为12.1.0.2的 ...
- 2016HUAS_ACM暑假集训2G - Who's in the Middle
这个题真的没什么好说的.一个排序就能解决的问题.唯一感到不爽的是这道题不是0msAC的,希望各位大神能够给我点指导. 头文件#include<algorithm>,注意一下排序函数的用法就 ...
- 关于清除丢失贴图与IES文件
fn YY_clrmessingmaps = ( YY_messingmap = #() allBitmaps = getClassInstances BitmapTexture -- 所有材质 to ...