我需要在后台运行应用程序的某些部分,并允许用户在子程序在后台运行时更新 UI。我搜索并发现在 WPF 中我应该使用 Dispatcher。问题是即使我使用调度程序,我的 GUI 仍然无法使用,直到所有潜艇都完成。我在这里附上了一个代码,这样你就可以更好地理解我的意思。例如,在这段代码中,当用户运行应用程序时,系统应该运行一个新线程来更改第一个文本框的文本,而使用可以更新第二个文本框的文本。我想知道我这样做是否正确。有人可以帮我吗?
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:testDispacher"
Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<StackPanel>
<TextBlock>UCtextbox:</TextBlock>
<src:ToBeRunByDispacherUC x:Name="UC1" />
<TextBlock>Windowstxtbox:</TextBlock>
<TextBox x:Name="txtBox2" Width="100" Height="30"/>
</StackPanel>
</Grid>
Class Window1
Delegate Sub runSub()
Dim setTxt As runSub
Public Sub New()
InitializeComponent()
setTxt = AddressOf UC1.setTxtBox
End Sub
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
UC1.IsEnabled = False
Dispatcher.Invoke(setTxt, Windows.Threading.DispatcherPriority.Background)
End Sub
结束类
<UserControl x:Class="ToBeRunByDispacherUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<TextBox x:Name="txtBox1" Width="100" Height="30"/>
</Grid>
Partial Public Class ToBeRunByDispacherUC
Public Sub setTxtBox()
Dim j As Integer = 0
For i As Integer = 0 To 10
j += 1
System.Threading.Thread.Sleep(1000)
Next
txtBox1.Text = "End"
Me.IsEnabled = True
End Sub
End Class