Reputation: 14743
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.
Upvotes: 3
Views: 1955
Reputation: 564821
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.
Upvotes: 6