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#中的多线程异常 (转载)的更多相关文章

  1. ArcGIS Engine 中的多线程使用[转载]

    一直都想写写AE中多线程的使用,但一直苦于没有时间,终于在中秋假期闲了下来.呵呵,闲话不说了,进入正题!         大家都了解到ArcGIS中处理大数据量时速度是相当的慢,这时如果你的程序是单线 ...

  2. C# 中的多线程(转载)

    关于多线程的系列,翻译自国外大牛的文章,值得推荐 原文地址:https://blog.gkarch.com/topic/threading.html

  3. [转载]ArcGIS Engine 中的多线程使用

    ArcGIS Engine 中的多线程使用 原文链接 http://anshien.blog.163.com/blog/static/169966308201082441114173/   一直都想写 ...

  4. C#多线程中的异常处理(转载)

    常规Thread中处理异常 使用Thread创建的子线程,需要在委托中捕捉,无法在上下文线程中捕捉 static void Main(string[] args) { ThreadStart thre ...

  5. 如何处理Entity Framework / Entity Framework Core中的DbUpdateConcurrencyException异常(转载)

    1. Concurrency的作用 场景有个修改用户的页面功能,我们有一条数据User, ID是1的这个User的年龄是20, 性别是female(数据库中的原始数据)正确的该User的年龄是25, ...

  6. 细说.NET 中的多线程 (一 概念)

    为什么使用多线程 使用户界面能够随时相应用户输入 当某个应用程序在进行大量运算时候,为了保证应用程序能够随时相应客户的输入,这个时候我们往往需要让大量运算和相应用户输入这两个行为在不同的线程中进行. ...

  7. 细说.NET中的多线程 (二 线程池)

    上一章我们了解到,由于线程的创建,销毁都是需要耗费大量资源和时间的,开发者应该非常节约的使用线程资源.最好的办法是使用线程池,线程池能够避免当前进行中大量的线程导致操作系统不停的进行线程切换,当线程数 ...

  8. Java多线程学习(转载)

    Java多线程学习(转载) 时间:2015-03-14 13:53:14      阅读:137413      评论:4      收藏:3      [点我收藏+] 转载 :http://blog ...

  9. 使用总结:java多线程总结 <转载>

    转载 https://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html java多线程总结 2011-08-28 20:08  Ro ...

随机推荐

  1. 微信 H5 支付流程以及一些坑

    原文:https://blog.niceue.com/front-end-development/wechat-h5-payment-process-as-well-as-some-pits.html ...

  2. 【读书笔记】iOS-处理内存警告

    -(void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning]; } 在这里你需要释放掉所有占用了很大内存的对象,如果你忽略了这个警告, ...

  3. 开发Hexo主题(一)

    Hexo是一款静态博客工具,由Node.js编写 在博客根目录的themes下,新建文件夹(文件夹名为主题名) 主题目录结构如图 这里使用模版引擎为Ejs 在Layout目录下新建index.ejs文 ...

  4. IDEA项目搭建八——使用MybatisPlus简化数据库交互

    一.MybatisPlus简化数据库交互 我们使用Mybatis发现需要在mapper.xml中写很多重复的简单CRUD(增删改查),使用MybatisPlus可以大大简化这部分代码,官方文档http ...

  5. 【Python】keras使用Lenet5识别mnist

    原始论文中的网络结构如下图: keras生成的网络结构如下图: 代码如下: import numpy as np from keras.preprocessing import image from ...

  6. 让bootstrap-table支持高度百分比

    更改BootstrapTable.prototype.resetView 方法,以支持高度百分比定义,适应不同高度屏幕 BootstrapTable.prototype.resetView = fun ...

  7. Linux 查看本机串口方法

    最近在了解嵌入式方面的知识,就随笔记录一下: 查看Linux本机串口: 1.查看串口是否可用 可以对串口发送数据比如对com1口,echo /dev/ttyS02.查看串口名称使用 ls -l /de ...

  8. java web中java和python混合使用

    利用java web技术展示python算法处理后的数据 工具/原料   myeclipse10 pycharm+Anaconda2 方法/步骤     首先安装配置好pycharm+Anaconda ...

  9. 禁用selinux

    查看selinux状态: [root@VM000000518 upload]# getenforce Enforcing 禁用: [root@VM000000518 upload]# setenfor ...

  10. 启用crontab

    1.登录到root用户. 2.在root下输入:crontab -e 3.可能会提示你: no crontab for root - using an empty one 然后会叫你“Select a ...