c#中的多线程异常 (转载)
1.对于Thread操作的异常处理
public static void Main()
{
try
{
Thread th = new Thread(DoWork);
th.Start();
}
catch (Exception ex)
{
// Non-reachable code
Console.WriteLine("Exception!");
}
} static void DoWork()
{
……
throw null; // Throws a NullReferenceException
}
在DoWork函数里抛出的异常时不会被主线程的try,catch捕捉的,各个线程应该有自己的try,catch去处理线程异常。
正确写法:
public static void Main()
{
Thread th = new Thread(DoWork);
th.Start();
} static void DoWork()
{
try
{
……
throw null; // The NullReferenceException will be 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"), "");
Console.ReadKey();
}
3 Task的异常处理
把try包含task.wait()函数,就能捕捉task的异常
Task task = Task.Run(() => { throw null; });
try
{
task.Wait();
}
catch (AggregateException aex)
{
if (aex.InnerException is NullReferenceException)
Console.WriteLine("Null!");
else
throw;
}
或者 在continue函数里处理TaskContinuationOptions.OnlyOnFaulted的状态
Task<List<int>> taskWithFactoryAndState =
Task.Factory.StartNew<List<int>>((stateObj) =>
{
List<int> ints = new List<int>();
for (int i = ; i < (int)stateObj; i++)
{
ints.Add(i);
if (i > )
{
InvalidOperationException ex =
new InvalidOperationException("oh no its > 100");
ex.Source = "taskWithFactoryAndState";
throw ex;
}
}
return ints;
}, ); //and setup a continuation for it only on when faulted
taskWithFactoryAndState.ContinueWith((ant) =>
{
AggregateException aggEx = ant.Exception;
Console.WriteLine("OOOOPS : The Task exited with Exception(s)");
foreach (Exception ex in aggEx.InnerExceptions)
{
Console.WriteLine(string.Format("Caught exception '{0}'",
ex.Message));
}
}, TaskContinuationOptions.OnlyOnFaulted); //and setup a continuation for it only on ran to completion
taskWithFactoryAndState.ContinueWith((ant) =>
{
List<int> result = ant.Result;
foreach (int resultValue in result)
{
Console.WriteLine("Task produced {0}", resultValue);
}
}, TaskContinuationOptions.OnlyOnRanToCompletion);
Console.ReadLine();
4 c# 5.0 中的async ,await 异常捕捉
static async Task ThrowAfter(int timeout, Exception ex)
{
await Task.Delay(timeout);
throw ex;
} static async Task MissHandling()
{
var t1 = ThrowAfter(, new NotSupportedException("Error 1"));
try
{
await t1;
}
catch (NotSupportedException ex)
{
Console.WriteLine(ex.Message);
}
}
c#中的多线程异常 (转载)的更多相关文章
- ArcGIS Engine 中的多线程使用[转载]
一直都想写写AE中多线程的使用,但一直苦于没有时间,终于在中秋假期闲了下来.呵呵,闲话不说了,进入正题! 大家都了解到ArcGIS中处理大数据量时速度是相当的慢,这时如果你的程序是单线 ...
- C# 中的多线程(转载)
关于多线程的系列,翻译自国外大牛的文章,值得推荐 原文地址:https://blog.gkarch.com/topic/threading.html
- [转载]ArcGIS Engine 中的多线程使用
ArcGIS Engine 中的多线程使用 原文链接 http://anshien.blog.163.com/blog/static/169966308201082441114173/ 一直都想写 ...
- C#多线程中的异常处理(转载)
常规Thread中处理异常 使用Thread创建的子线程,需要在委托中捕捉,无法在上下文线程中捕捉 static void Main(string[] args) { ThreadStart thre ...
- 如何处理Entity Framework / Entity Framework Core中的DbUpdateConcurrencyException异常(转载)
1. Concurrency的作用 场景有个修改用户的页面功能,我们有一条数据User, ID是1的这个User的年龄是20, 性别是female(数据库中的原始数据)正确的该User的年龄是25, ...
- 细说.NET 中的多线程 (一 概念)
为什么使用多线程 使用户界面能够随时相应用户输入 当某个应用程序在进行大量运算时候,为了保证应用程序能够随时相应客户的输入,这个时候我们往往需要让大量运算和相应用户输入这两个行为在不同的线程中进行. ...
- 细说.NET中的多线程 (二 线程池)
上一章我们了解到,由于线程的创建,销毁都是需要耗费大量资源和时间的,开发者应该非常节约的使用线程资源.最好的办法是使用线程池,线程池能够避免当前进行中大量的线程导致操作系统不停的进行线程切换,当线程数 ...
- Java多线程学习(转载)
Java多线程学习(转载) 时间:2015-03-14 13:53:14 阅读:137413 评论:4 收藏:3 [点我收藏+] 转载 :http://blog ...
- 使用总结:java多线程总结 <转载>
转载 https://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html java多线程总结 2011-08-28 20:08 Ro ...
随机推荐
- cdn原理的理解
今天要做个小笔记,浅谈一下对cdn的一些理解,在工作中我们经常用到cdn代理访问,那他的原理是什么不知道大家有没有考虑过 CDN的基本原理是广泛采用各种缓存服务器,将这些缓存服务器分布到用户访问相对集 ...
- VUE路由转场特效,WebAPP的前进与后退
一.效果图 二.思路 1. 定义两个 CSS 过度动画,前进与后退: slide-right-enter 和 slide-left-enter 2. 给路由配置meta信息,设置各个路由的级别 ...
- Android学习笔记----ArcGIS在线地图服务(Android API)坐标纠偏
仅限于如下ArcGIS在线地图服务(高德提供数据): //概述:彩色中文含兴趣点版中国基础地图 //投影:WGS 1984 Web-Mercator //切片格式:MIXED90 //服务类型:基础地 ...
- spring 使用外部属性文件
一.PropertyPlaceholderConfigurer spring提供的PropertyPlaceholderConfigurer实现类能够使Bean在配置时引用外部属性文件. Proper ...
- js replace替换 忽略大小写问题
实现就是控制台的内容“abc”,但是后台返回的是“ABC”,这个时候在前台遍历,需要将后台返回的在控制台标红. 当然控制台可以是 abc Abc等大小写混合,以下代码都可替换. var flagnew ...
- nslookup debug
Try adding forwarders to some public DNS servers leave the box ticked which says use root hints if f ...
- NFS服务搭建与配置
启动NFS SERVER之前,首先要启动RPC服务(CentOS5.8下为portmap服务,CentOS6.6下为rpcbind服务,下同),否则NFS SERVER就无法向RPC服务注册了.另外, ...
- 解决Windows10或者其他版本Windows Update报错的问题
最近更新系统,发现报错0x80248014,系统版本为redstone2(创意者更新). 总结发现,只要是windows各个版本自动更新报错的,如0x80开头的一系列错误,都可以通过如下步骤解决: 手 ...
- Alpha冲刺! Day3 - 砍柴
Alpha冲刺! Day3 - 砍柴 今日已完成 晨瑶:补充安卓技能树: review接口文档:看了点七牛云安卓API. 昭锡:没有团队项目相关贡献. 永盛: API 文档基本完成:根据 API 文档 ...
- i.s.h.med Enhancement for cancelling an appointment
This article intends to introduce my experience about enhancement for canceling an appointment. I tr ...