在WPF中处理第二个UI线程 [英] Handling a second UI thread in WPF
问题描述
我在UI线程上运行的进程很长,无法移出UI线程.相反,我试图创建另一个具有等待动画的UI线程.这是我用来创建第二个UI线程的代码:
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
如何在需要时正常关闭此窗口?我无法从主UI线程访问_waitWindow
来将其关闭.如果我发出_busyThread.Abort()
,它实际上并没有关闭窗口.
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.
推荐答案
您需要使用Dispatcher.BeginInvoke
关闭窗口:
这将使将窗口关闭到新窗口线程中的调用进行封送处理.
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.
请注意,从长远来看,弄清楚如何将长时间运行的进程移出主线程将是一个更好的解决方案,因为这仍然会使您的应用程序对Windows和最终用户无响应.
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.
这篇关于在WPF中处理第二个UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!