• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5107
  • Last Modified:

Delegate to an instance method cannot have null 'this'.

I'm trying to convert my multi-threaded application over to delegates so that it is thread safe. I'm getting the error "Delegate to an instance method cannot have null 'this'".

This is on the UI Thread,

   Public Sub UpdateStatusLabelMethod(ByVal strMessage As String())

 Dim intLabel As Integer = strMessage(0)
        Dim strStatusMessage = strMessage(1)

 TabControl1.TabPages(2).Text = strStatusMessage
   End Sub

The text is updated successfully.

This is the code within the worker thread class,

Delegate Sub UpdateStatusLabelHandler(ByVal strMessage As String())

Private Sub GetAnswer
     Dim argsStatus As String() = {WorkerCount, "[" & intTried & "]." & strDots}

End Sub

   Public Sub UpdateStatusLabel(ByVal strMessage As String())

        Dim f As Form1 = My.Forms.Form1.ActiveForm
        f.Invoke(New UpdateStatusLabelHandler(AddressOf f.UpdateStatusLabelMethod), _
                 New Object() {strMessage})
    End Sub

  • 2
1 Solution
Göran AnderssonCommented:
You failed to get a reference to the form. The reference f is Nothing, and you can't use a method in an object that doesn't exist.

Check what you get from the ActiveForm property before you try to use it.
JPERKS1985Author Commented:
does it mean that sometimes it can't find it, but other times it can?
Göran AnderssonCommented:

From the documentation of the ActiveForm property:

"Property value:
A Form that represents the currently active form, or a null reference (Nothing in Visual Basic) if there is no active form."

Also, you are implicitly casting the return value of the property from the class Form to the class Form1. If the active form is of a different class that will not work. You should set Option Strict On to avoid unintentional casting in your code.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now