简体   繁体   English

未从 try-catch 块内部捕获“未处理”异常

[英]“Unhandled” Exception not being caught from inside a try-catch block

I am attempting to run an async output that will last a large amount of time, and then closing the application during execution which causes the textbox to dispose.我正在尝试运行将持续很长时间的异步 output,然后在执行期间关闭应用程序,这会导致文本框被释放。 I thought this would be handled by simply returning in a try-catch statement, but VS still says there is an "unhandled" exception.我认为这可以通过简单地返回 try-catch 语句来处理,但 VS 仍然说存在“未处理”异常。 Here is the code:这是代码:

public void AppendOutput(string text)
    {
        var timeNow = DateTime.Now;

        if ((DateTime.Now - previousTime).Milliseconds <= 50) return;
        try
        {
            synchronizationContext.Post(new SendOrPostCallback(o =>
            {
                Output.AppendText((string)o);
            }), text);
        }
        catch(ObjectDisposedException e)
        {
            return;
        }

        previousTime = timeNow;
    }

Here is what happens in debug:以下是调试中发生的情况: 调试中会发生什么

I there a reason why this is considered unhandled?我有理由认为这是未处理的吗? I thought that's what try-catch was for.我以为这就是 try-catch 的用途。 My understanding was that I could simply return because there's no need to handle exceptions for a program that is attempting to write to a textbox that has been disposed;我的理解是我可以简单地返回,因为没有必要为试图写入已处理的文本框的程序处理异常; the program should be ending the thread on its own.程序应该自行结束线程。 What is the correct way to deal with this problem?处理这个问题的正确方法是什么?

According to your description, you want to solve the abnormal problem that occurs during debugging.根据您的描述,您想解决调试过程中出现的异常问题。

You can add the following code in the initialization component function, as shown below:可以在初始化组件function中添加如下代码,如下图:

public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

Result:结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM