title: Threading and modal form windows
body: <p>VB.Net code.</p>
  <p>I have a program where I am running a process in a thread and in that thread I need to have a pop up message information box that is non-modal. The main process is in a thread because it has to run in parallel and the user can initiate this process many times at the same time.</p>
  <p>I read that the modal message box needs to be a custom form that is also ran from a thread to not block the program from continuing on. such as .Show() stops the program and waits for the user input. And you have to use .ShowDialog() via a thread</p>
  <p>My code:</p>
  <p>Calling initial thread:</p>
  <pre><code>Public Event Report As EventHandler
   
     'In a method
      Task.Run(Function() BackgroundThread())
      
  
  Private Function BackgroundThread() As Task()
       RaiseEvent Report(Me, New System.EventArgs)
  End Function
  </code></pre>
  <p>In the Report method I have a snippet of code that then calls the form window to pop up the modal window:</p>
  <pre><code>Private mDiaplayMessageBox As NonModalPopUp
  
  Private Sub DisplayMessageBox()
          mDiaplayMessageBox = New NonModalPopUp()
          Task.Run(Sub() mDiaplayMessageBox.ShowDialog())
  End Sub
  </code></pre>
  <p>The issue I am having is that when I am finished with the report method I want to close this popup message. But when there is more than one of these pop up windows open at a time, only the last window opened will close and the program loses the handle I think to the other pop up windows and they will not close.</p>
  <p>To close the windows I have in the modal form this code</p>
  <pre><code>Public Sub CloseMe()
          'This will grab the thread that this window is running on, solves Cross-Threading issue.
          If Me.InvokeRequired Then
              Me.Invoke(New MethodInvoker(AddressOf CloseMe))
              Exit Sub
          End If
          Me.BackColor = Color.Red
  
          Me.Close()
  End Sub
  </code></pre>
  <p>This first time this code is called its will hit the Me.Invoke and then close the window. However, on any subsequent calls when it gets to Me.InvokeRequired this will then be set to false, not called the Me.Invoke and go to the Me.Close() but it will not close the window.</p>
  <p>I tried to do something where I grab the Handle intptr value but when ever I vent just look at that value the program immediately throws a cross-threading exception.</p>
  <p>All I want to do is close the other windows which does not seem like a hard task but I do not know what I am missing.</p>