线程通知异常的另一个THEAD

编程入门 行业动态 更新时间:2024-10-22 17:25:36
本文介绍了线程通知异常的另一个THEAD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

的ThreadA产卵ThreadB。

ThreadB抛出异常。

如何ThreadA中了解这个例外

使用系统?; 使用的System.Threading; 命名ConsoleApplication1 {类节目 {静态无效的主要(字串[] args) {的ThreadStart threadDelegate1 =新的ThreadStart( MyClass1.DoThis); 线程的ThreadA =新主题(threadDelegate1); ThreadA.Start(); Thread.sleep代码(100000); //此线程人在这里做什么,睡觉模拟它 } } 类MyClass1的 {公共静态无效DoThis() {试 {的ThreadStart threadDelegate1 =新的ThreadStart(MyClass2.DoThat); 螺纹ThreadB =新主题(threadDelegate1); ThreadB.Start(); Thread.sleep代码(100000); //此线程人在这里做什么,睡觉模拟它 } 赶上(例外五) { //我想知道,如果出事了与MyClass2.DoThat } } } 类MyClass2 {公共静态无效找时间做() $ { b $ b抛出新的异常(从找时间做吧); } } }

解决方案

下面是一种方法,使用的ManualResetEvent和lambda表达式:

试 {异常EXC ; 使用(ManualResetEvent的resetEvent =新的ManualResetEvent(假)) {螺纹ThreadB =新的Thread(()=> {试 { MyClass2.DoThat(); } 赶上(例外五) { EXC = E; resetEvent.Set(); } }); ThreadB.Start(); 如果(resetEvent.WaitOne(10000)) {扔EXC; } } } 赶上(例外五) { //我想知道,如果出现了一些问题MyClass2.DoThat }

您可以打扫一下,当然这取决于你希望具体做什么。

ThreadA spawns ThreadB.

ThreadB throws an exception.

How can ThreadA know about this exception?

using System; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ThreadStart threadDelegate1 = new ThreadStart(MyClass1.DoThis); Thread ThreadA = new Thread(threadDelegate1); ThreadA.Start(); Thread.Sleep(100000); // this thread is doing something else here, sleep simulates it } } class MyClass1 { public static void DoThis() { try { ThreadStart threadDelegate1 = new ThreadStart(MyClass2.DoThat); Thread ThreadB = new Thread(threadDelegate1); ThreadB.Start(); Thread.Sleep(100000); // this thread is doing something else here, sleep simulates it } catch (Exception e) { // I want to know if something went wrong with MyClass2.DoThat } } } class MyClass2 { public static void DoThat() { throw new Exception("From DoThat"); } } }

解决方案

Here is one way, using ManualResetEvent and lambdas:

try { Exception exc; using (ManualResetEvent resetEvent = new ManualResetEvent(false)) { Thread ThreadB = new Thread(() => { try { MyClass2.DoThat(); } catch (Exception e) { exc = e; resetEvent.Set(); } }); ThreadB.Start(); if (resetEvent.WaitOne(10000)) { throw exc; } } } catch (Exception e) { // I want to know if something went wrong with MyClass2.DoThat }

You can clean this up, surely depending on what you want to do specifically.

更多推荐

线程通知异常的另一个THEAD

本文发布于:2023-11-11 23:32:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579843.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   异常   通知   THEAD

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!