本文介绍了代表和例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 大家好, 我一直在试验代表和例外。 我知道当一个单独的线程发生异常时 在调用EndInvoke时保存并检索它,但 为什么我不能重新抛出它? 问候, 示例代码: class应用 { delegate void MyDelegate(); static void Main(string [] args) { 应用程序app =新应用程序(); app.Start(); Console.ReadLine(); } public void Start() { MyDelegate myDelegate = new MyDelegate(BadMethod); myDelegate.BeginInvoke(new AsyncCallback (DelegateCallback),myDelegate); } public void BadMethod() { string newstring = string 。空; if(newstring.Length == 0) { 抛出新的ApplicationE xception(" delegate 测试例外); } } private void DelegateCallback(IAsyncResult ar ) { MyDelegate result =(MyDelegate)ar.AsyncState; try { result.EndInvoke(ar); } catch { 抛出; } } } 解决方案 你可以 - 你认为你不能做什么? 请注意,在您的示例中,当您重新抛出异常时,没有任何内容报告它,因为它在线程池线程中没有任何额外的 异常处理程序。 - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复该群组,请不要给我发邮件 rethrown时,没有任何报告,因为它在线程池线程中没有任何额外的处理程序。 - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复该群组,请不要邮寄我也是。 线程池本身捕获并吞下它上面抛出的所有异常 个线程,所以你不会得到一个未处理的异常。你需要捕获所有 你的线程池回调例程抛出的异常然后 使用你自己的机制传播那个异常。你可以排队, 立即报告,等等。 Hi All, I have been experimenting with delegates and exceptions.I know that when an exception occurs on a separate threadit is saved and retrieved when EndInvoke is called, butwhy can''t I rethrow it? Regards, Example Code: class Application{delegate void MyDelegate(); static void Main(string[] args){Application app = new Application();app.Start(); Console.ReadLine();}public void Start(){MyDelegate myDelegate = new MyDelegate(BadMethod); myDelegate.BeginInvoke(new AsyncCallback(DelegateCallback), myDelegate);}public void BadMethod(){string newstring = string.Empty; if (newstring.Length == 0){throw new ApplicationException("delegatetesting exception");}}private void DelegateCallback(IAsyncResult ar){MyDelegate result = (MyDelegate) ar.AsyncState; try{result.EndInvoke(ar);}catch{throw;}}} 解决方案 You can - what makes you think you can''t? Note that in your example, when your exception is rethrown, nothing isreporting it because it''s in a threadpool thread without any extraexception handlers. --Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me toorethrown, nothing isreporting it because it''s in a threadpool thread withoutany extraexception handlers.--Jon Skeet - <sk***@pobox.com>http://www.pobox.com/~skeetIf replying to the group, please do not mail me too.The threadpool itself catches and swallows all exceptions thrown on itsthreads, so you will not get an unhandled exception. You need to catch allthe exceptions thrown in your threadpool callback routine and thenpropagate that exception using your own mechanism. You can queue it up,report it immediately, etc. 这篇关于代表和例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-26 18:41