Try/Catch and threading

前端 未结 5 945
谎友^
谎友^ 2021-02-07 13:29

I have an idea why but I\'d like to ask if someone has a good grasp on why the exception raised inside a thread is never caught by the code that started it. Here\'s some very si

相关标签:
5条回答
  • 2021-02-07 13:59

    You might want to use an EventGeneratingThread wrapper - this will let you catch and deal with exceptions thrown in threads from the process that spawned them.

    0 讨论(0)
  • 2021-02-07 14:00

    The running thread will not be caught in your try/catch statement because it is running in another thread. Try/Catch only works for the current thread. What you need to do is have try/catch in the function being run by the thread, and have some way of managing what happens when that crash occurs.

    0 讨论(0)
  • 2021-02-07 14:05

    Well in general, you've no idea where the originating thread will be by the time the exception is thrown in the new thread - why would it be waiting around for the thread to throw an exception?

    Think of the stacks involved - when an exception is thrown, it goes up the stack until it reaches an appropriate catch block. The new thread has a completely separate stack to the creating thread, so it'll never reach the catch block in the creating thread's stack.

    EDIT: Of course, you could design your system so that the creating thread did wait for other things to happen - a bit like the message loop in a Windows Forms application. The new thread could then catch the exception and send a message to the creating thread, which could then deal with the exception. That isn't the normal setup though - you have to do it all explicitly.

    0 讨论(0)
  • 2021-02-07 14:06

    It's a bad idea to make assumptions, especially where multiple threads are involved (you know that old saying).

    Why would the code that started the thread see the exception? The code that started the thread may not even exist when the exception is thrown.

    0 讨论(0)
  • 2021-02-07 14:11

    Try adding this before your DoWork Sub

    <System.Diagnostics.DebuggerNonUserCodeAttribute()> _
    

    I'm using the background worker, and all the Try Catch in my loop work as you'd expect them to with this.

    0 讨论(0)
提交回复
热议问题