Share via

Same code with different behaviors!

Sani Love 160 Reputation points
2023-12-22T20:40:06.3433333+00:00

Hello

In the same form, but in 2 different placess which both start with on error resume next, on one SUB, this code is fine and will compile:

If blah.InvokeRequired Then
 Invoke(Sub() blah.Text = String.Empty)
Else
 blah.Text = String.Empty
End If

But under an event SUB will cause error:

BC36595 Method cannot contain both a 'On Error Resume Next' statement and a definition of a variable that is used in a lambda or query expression.

This terrible behavior/error started since vs 2015 but they even couldn't implement it correctly!

How the same code under 2 subs will have different behaviors?! Using latest vs 2022.

Developer technologies | VB

2 answers

Sort by: Most helpful
  1. Jiachen Li-MSFT 34,241 Reputation points Microsoft External Staff
    2023-12-25T11:34:38.6333333+00:00

    Hi @Sani Love ,

    The issue arises because On Error Resume Next and lambda expressions (used within the Invoke method) cannot coexist within the same method. The lambda expression captures the context where it's defined, and this conflicts with the error handling provided by On Error Resume Next.

    Make sure UI updates happen on the UI thread.

    If blah.InvokeRequired Then
        blah.Invoke(Sub() UpdateText(blah, String.Empty))
    Else
        blah.Text = String.Empty
    End If
    
    ' Define a separate method to update the text
    Private Sub UpdateText(ByVal control As Control, ByVal text As String)
        If control.InvokeRequired Then
            control.Invoke(Sub() UpdateText(control, text))
        Else
            control.Text = text
        End If
    End Sub
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    0 comments No comments

  2. gekka 14,146 Reputation points MVP Volunteer Moderator
    2023-12-23T03:45:30.6566667+00:00

    If you call Control.Invoke from a non-main thread, it will be executed in the main thread.

    Errors occurring in another thread cannot be caught. Any errors that occur must be handled within that thread.

    On Error Resume Next
    
    If blah.InvokeRequired Then
        blah.Invoke(Sub()
                        Try
                            Throw New ApplicationException()
                        Catch ex As Exception
    
                        End Try
    
                    End Sub)
    Else
        blah.Text = String.Empty
    End If
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.