专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »博文摘选 » 统一的线程异常处理 »正文

统一的线程异常处理

来源: 发布时间:星期六, 2009年12月26日 浏览:0次 评论:0
个Service 通常都会有多个Worker线程它们可能单独运行 也可能在个ThreadPool中运行为了不至于使Worker线程未处理异常导致主崩溃我们需要对所有工作线程以方式处理异常例如通知主线程然后根据区别异常做区别处理最后优雅地停止该有问题线程 例如以下:

void Main( args) { Thread thread1 = Thread((ThreadStart)Worker_1); thread1.Start; Thread thread2 = Thread((ThreadStart)Worker_2); thread2.Start; thread1.Join; thread2.Join; } void Worker_1 { try { // Do something here. } catch (Exception e) { // TODO, handler exception, // Noty the thread and stop this thread gracefully. } } void Worker_2 { try { // Do something here. } catch (Exception e) { // TODO, handler exception, // Noty the thread and stop this thread gracefully. } }



在该我们有 Worker_1 和 Worker_2两个工作线程它们有相同异常处理过程但是问题是当任务种类多了起来如Worker_3, Worker_4 所有这样线程都要做相同异常处理就导致了不必要重复并且很容易遗忘怎样去除这种重复呢?首先想到个方案是提供个辅助它接受个Action作为参数:

void SafeThread(Action action) { try { action; } catch (Exception e) { // TODO, handler exception, // Noty the thread and stop this thread gracefully. } }



然后Worker_1 可以这么写:

void Worker_1 { SafeThread(delegate { // Do something here. }); }



这样是能简化但这种做法会使原来Worker思路方法有个奇怪包装而且依然要求我们对每个Worker做同样处理既然Thread构造接受个 ThreadStart参数我们能不能把个原始直接Worker 思路方法(也是 ThreadStart类型)转换为个可以处理异常 ThreadStart 类型呢? 是可以首先我们定义这个转换如下:

ThreadStart SafeThread(ThreadStart threadStart) { => { try { threadStart; } catch (Exception e) { // TODO, handler exception, // Noty the thread and stop this thread gracefully. } }; }

 

那么我们Worker线程会很直接:

void Worker_1 { Console.WriteLine("Worker 1"); // Do something here. } void Worker_2 { Console.WriteLine("Worker 2"); // Do something here. }



而主则需要稍加改动但也非常简单:

void Main( args) { Thread thread1 = Thread(SafeThread(Worker_1)); thread1.Start; Thread thread2 = Thread(SafeThread(Worker_2)); thread2.Start; thread1.Join; thread2.Join; }

 

这对线程编写者来说 减轻了很多负担 也不至于会遗漏掉某个线程没被处理次简单搜索就可以解决问题

对于接受个参数线程(ParameterizedThreadStart)和线程池线程 (WaitCallback)我们又该如何处理呢?

标签:
0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: