(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是一个轻量级的可扩 ...
随机推荐
- 高版本正方教务系统上传后缀过滤不严导致能直接上传Webshell
在旧版本中有一个利用插件上传文件的漏洞,但是在新版本中已经没有了这个插件.这个漏洞是由于过滤不严造成的,可以直接上传Webshell进行提权,由于代码在DLL中,全国大部分高校均有此漏洞,影响范围很大 ...
- mysql 处理查询请求过程
需要搞清楚查询为什么会慢,就要搞清楚mysql处理查询请求的过程: 1.客户端发送SQL请求给服务器 2.服务器检查是否可以在查询缓存中命中该SQL 查询缓存对SQL性能的影响. 1.需要对缓存加 ...
- Octopus系列之代码备份
代码 $.extend($.validator.messages, { required: "This field is required.", remote: "Ple ...
- C# Enum 简易权限设计 使用FlagsAttribute属性
基本權限設計: /// <summary> /// 權限列舉 /// </summary> [FlagsAttribute] public enum Permissions { ...
- UDK:AdventureKit 攀爬系统
[目标] AdventureKit攀爬系统 [思路] [步骤] 1 拷贝 2 设置config,UDKGame\Config\DefaultEngine.ini 添加包 [UnrealEd.Edito ...
- 如何替换掉.net toolStrip控件溢出按钮背景图
在使用.net toolStrip控件的时候, toolStrip里面的item宽度超过本身宽度时,会出现一个溢出按钮:OverflowButton,这个按钮是控件的一个属性,其实也是继承自Tool ...
- 爱壁纸 站立会议(六)--Spring阶段总结会议
爱壁纸 站立会议(六)--Spring阶段总结会议 一.会议时间 2014年4月15日 星期三 21:00-21:20 今天是spring阶段最后一天,大家都对这一星期的任务概况做出了总结所以时间稍微 ...
- candence 知识积累1
Allegro 总结: 1.防焊层(Solder Mask):又称绿油层,PCB非布线层,用于制成丝网印板,将不需要焊接的地方涂上防焊剂.在防焊层上预留的焊盘大小要比实际的焊盘大一些,其差值一般为10 ...
- ASP.NET——生成验证码
实现:随机生成四位数字的验证码,点击验证码可无刷新生成新的验证码,最后点击按钮进行检验 PS:本实例使用UpdatePanel实现无刷新. 前台代码: <asp:ScriptManager ID ...
- Nested List Weight Sum -- LeetCode 339
Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...