3

I have a long running process that runs on my UI thread that I cannot move off of the UI thread. Instead I am trying to create a second UI thread that has a waiting animation. Here's the code I'm using to create the second UI thread:

Private _busyThread As Thread
Private _waitWindow As WaitWindow 'This is the window with the animation

Private Sub StartBusyIndicator(ByVal busyInfo As BusyInfo)
    _busyThread = New Thread(New ThreadStart(AddressOf ThreadStartingPoint))
    _busyThread.SetApartmentState(ApartmentState.STA)
    _busyThread.IsBackground = True
    _busyThread.Start()
End Sub

Private Function ThreadStartingPoint() As ThreadStart
    _waitWindow = New WaitWindow
    _waitWindow.Show()
    System.Windows.Threading.Dispatcher.Run()
End Function

How can I close this gracefully when needed? I can't access _waitWindow from the main UI thread to close it. If I issue _busyThread.Abort() it doesn't actually close the window.

3
  • 2
    If your design insists on running on the UI thread something is probably wrong with it and it's most likely possible to refactor it such that you still have just one UI thread. In the extremely improbable case you really need a second UI thread you can always run a separate process and use named pipes to communicate between the two Commented Aug 5, 2013 at 21:09
  • What is the long running process doing on the UI thread? Reed is correct that the process should be moved off the UI. Commented Aug 5, 2013 at 21:10
  • Yes, it does need refactoring. I was looking for a quick fix until that time. Commented Aug 6, 2013 at 0:11

1 Answer 1

6

You would need to use Dispatcher.BeginInvoke to close the window:

This marshals the call to close the window into the new window's thread.

This will not shut down that thread, though. To do that, try:

_waitWindow.Dispatcher.BeginInvoke(Sub()
         _waitWindow.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background)
         _waitWindow.Close()
    End Sub)

I have an article on my blog which discusses this, as well as other issues, in detail. It's in C#, but could be converted to VB.Net easily enough.

Note that, in the long run, figuring out how to move the long running process off the main thread will be a better solution, as this will still leave your application as appearing unresponsive to Windows and your end user.

Sign up to request clarification or add additional context in comments.

3 Comments

Should I actually abort the 2nd thread then? Or will it clean itself up?
@MikeCole Showed how to handle this.
Great blog post. Was there ever a part 2?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.