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 ...
随机推荐
- 【代码笔记】Web-HTML-段落
一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...
- 【读书笔记】iOS-访问网络
iOS平台是按照一直有网络连接的思路来设计的,开发者利用这一特点创造了很多优秀的第三方应用.大多数的iOS应用都需要联网,甚至有些应用严重依赖网络,没有网络就无法正常工作. "在访问网络失败 ...
- Power BI 与 Azure Analysis Services 的数据关联:1、建立 Azure Analysis Services服务
Power BI 与 Azure Analysis Services 的数据关联:1.建立 Azure Analysis Services服务
- 安卓开发_WebView设置打开网页缩放问题
之前实现打开网页的方式,测试后,发现不能够对网页进行缩放操作,这对部分网页来说是十分不便的, 百度了一下解决方案 其实只需要加几行代码就可以实现网页缩放操作 settings.setUseWideVi ...
- Android View体系(五)从源码解析View的事件分发机制
1.处理点击事件的方法 View的层级 我们知道View的结构是树形的结构,View可以放在ViewGroup中,这个ViewGroup也可以放到另一个ViewGroup中,这样层层的嵌套就组成了Vi ...
- 分享一下我研究SQLSERVER以来收集的笔记
分享一下我研究SQLSERVER以来收集的笔记 前言 为什麽分享??因为像现在网上很多人攻城师那样,转行去卖水果,卖早餐,总有一日我也会离开这个行业的 由于本人不是在大公司上班工资很低,我希望有一天存 ...
- 使用 PsPing & PaPing 进行 TCP 端口连通性测试
PsPing & PaPing 介绍 通常,我们测试数据包能否通过 IP 协议到达特定主机时,都习惯使用 ping 命令.工作时 ping 向目标主机发送一个 IMCP Echo 请求的数据包 ...
- 7z常用命令行&7z检测压缩包完整性&7z压缩包错误不执行rsync同步
7Z简介&常用命令 7Z脚本使用说明 7Z检测压缩包完整性脚本 7Z压缩包错误不执行Rsync脚本 1.7Z简介&常用命令 ⑴简介: 7z,全称7-Zip, 是一款开源软件.是目前公认 ...
- VScode启动后cup100%占用的解决方法
新安装的vscode,版本1.29.1.启动后,cpu占用一直是100%,非常的卡.百度以下,找到了解决方法,整理一下. 解决方法:在VScode中文件->首选项->设置->搜索-& ...
- MySQL基本简单操作01
MySQL基本简单操作 学会了安装Docker,那么就将它利用起来.(/滑稽脸) 之前想学习Mysql(Windows下配置真麻烦),学会了Docker就方便了,直接使用Docker创建一个Mysql ...