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. 腾讯云部署golang flow流程,vue.js+nginx+mysql+node.js

    这次总算把js-ojus/flow的ui部署到腾讯云上,比较吐槽的就是,为啥这么复杂,vue.js前后端分离,比golang编写的部署方面复杂几万倍.真是浪费人生啊. golang+sqlite写的东 ...

  2. Log4J Appender - 将Log4J的日志内容发送到agent的source

    项目中使用log4j打印的内容同时传输到flume 1.flume端 flume的agent配置内容如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 a1.sour ...

  3. typescritp 导出默认接口

    假如有ITest.ts文件,如下: export default interface ITest{ } 这样会报错,编译不通过.据说是设计成这样的,具体详细见:https://github.com/M ...

  4. LeetCode题解之Diameter of Binary Tree

    1.题目描述 2.分析 深度优先. 3.代码 int ans; int diameterOfBinaryTree(TreeNode* root) { ans = ; depth(root); ; } ...

  5. 安装Linux Mint 17后要做的20件事

    Linux Mint 17 Qiana Cinnamon Linux Mint 17已经发布,定名为Qiana.Mint是Linux最佳发行版之一,它定位于桌面用户,关注可用性和简洁.它携带了风格迥异 ...

  6. [20171120]bash使用here documents的一个小细节.txt

    [20171120]bash使用here documents的一个小细节.txt --//昨天看bash文档,,发现一些小细节,做一个记录,就是EOF加引号的问题. command <<' ...

  7. 【 PostgreSQL】查询某模式下所有表的分布键信息

    想看下某模式下所有表创建的分布键是否合理,查找系统表文档拼出如下sql,亲们如果有更好的sql或者意见欢迎留言! ​SELECT     aaa.nspname AS "模式名", ...

  8. Json Schema的使用

    直接上案例: 在Web Api通讯中,客户端发送json数据,服务端反序列化json(json与某个类形成对应关系),在某些情况下,需要校验其上传的json是否合法. 服务端是使用Json.net(n ...

  9. jenkins离线插件安装--笨方法

    Jenkins离线安装插件有多种方式:代理or离线导入,但离线导入可能会存在版本差异或依赖的插件文件导致异常发生), 以下为笨方法但会很准确的解决以上的问题. 同版本Jenkins在线下载:模糊掉的是 ...

  10. nginx limit_rate突然限速失败

    ##问题 nginx限制用户对指定目录的访问: <!-- lang: shell --> location ~ ^/(path001)/ { limit_rate 0k; limit_co ...