0

Background: I have multithreaded application that has one main UI thread and two threads that are super loops that run for the duration of the program. The worker threads basically read in some information and write an output to a Program Logic Controller.

I am running into an issue that I can't repeat when I'm debugging but only happens when the program is compiled and ran as an executable. I know the proper way of dealing with my issue is to find out why this is happening and deal with it. But while I am doing that I was wondering if it was possible to handle this issue in a different way...

Quesiton : My entire worker thread is in a

    Try
    Catch ex As Exception
    Finally
    End Try

Is it good practice / and even possible for me to dispose of my worker thread in the catch when it hits an exception and then restart / reinstantiate itself in the finally block?

I would Imagine a response to this might be "No thats not good practice because if you hit the exception mid loop, you will lose all the states of all your objects in your thread and if you restart it it might throw things out of sync."

This isn't actually going to be a problem for me, because all the states of all my objects are updated real time on the PLC, and the very first thing I do when I start my worker thread is read from the PLC to get all the states of all my objects.

The root of my question is, can a thread restart itself in the finally block?

4

3 回答 3

3

如果您从此更改了线程代码

    Do While True
        'your code here
    Loop

对此

    Do While True
        Try
            'your code here
        Catch ex As Exception

        End Try
    Loop

那么只有当你有一个 Exit Do 或者 catch 块中的代码抛出异常时,线程才能退出。

于 2013-06-17T13:11:21.147 回答
2

这绝对不是好的做法,但可以做到。但是,您可能希望在 Catch 块中重新启动它,而不是在 finally 块中。finally 块在 Catch 结束时被调用,但如果 Try 块完成执行,它也会被调用。

于 2013-06-17T12:57:06.947 回答
1

具体回答您的问题;可能吗?是的 - 你可以这样做:

Public Sub Main
    'define thread object outside the Try block so we can use it 
    'again in the Catch block
    Dim thr as Thread
    Try
        thr = New Thread(AddressOf SuperLoop1)
        thr.Start
    Catch
        'you may want to log the exception so you know it has happened
         thr = New Thread(AddressOf SuperLoop1)
        thr.Start
    End Try
End Sub

Sub SuperLoop1
    'code for "super loop 1"
End Sub
于 2013-06-17T13:28:22.883 回答