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 ...
 
随机推荐
- 【读书笔记】iOS-iOS的持续集成
			
一,Jenkins http://jenkins-ci.org 二,iOS单元测试的持续集成 在Xcode进入OCUnit作为单元测试框架前,把单元测试分为两种:Logic Test和Applicat ...
 - docker 搭建maven 私服
			
# 搜索镜像 docker search nexus; #拉取nexus镜像docker pull sonatype/nexus; #运行 -id 创建守护式容器--privileged=true 授 ...
 - 读懂SAP Leonardo物联网平台
			
读懂SAP Leonardo物联网平台 https://blog.csdn.net/weixin_42137700/article/details/81903290 本文比较系统.全面地介绍了SAP ...
 - Android View体系(五)从源码解析View的事件分发机制
			
1.处理点击事件的方法 View的层级 我们知道View的结构是树形的结构,View可以放在ViewGroup中,这个ViewGroup也可以放到另一个ViewGroup中,这样层层的嵌套就组成了Vi ...
 - (网页)jQuery的时间datetime控件在AngularJs中使用实例
			
百度一下,自己也想了一下,有一种简单,无脑的方式分享给你: <input ng-model="start" id="start" placeholder= ...
 - github版本控制相关
			
Git版本控制: 安装Github http://blog.csdn.net/huangyuan_xuan/article/details/49125597 Git本地版本控制 http://blog ...
 - C#微信公众号开发——获取access_token
			
access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token.正常情况下access_token有效期为7200秒(两个小时),微信获取access_token接 ...
 - C# RSA 加密
			
class Sign_verifySign { #region prepare string to sign. //example format: a=123&b=xxx&c (wit ...
 - python  pip 使用时错误: Patal error in launcher:Unable to create process using '"'
			
当前我的电脑配置是64位, 装有python2.7 和python 3.6 两个版本 在使用pip install mysqlclient 的时候,出现了 Patal error in launch ...
 - ws协议的配置
			
server { listen 80; server_name 域名或IP; rewrite ^(.*)$ https://$host$1 permanent; } server { listen 4 ...