16,554
社区成员
发帖
与我相关
我的任务
分享
Private Sub Button_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim t As New TestClass
Me.DataContext = t
Dim th As New System.Threading.Thread(Sub()
计算程序1()
Me.Dispatcher.BeginInvoke(New Action(Sub() t.Text = "进度消息1"))
System.Threading.Thread.Sleep(1000)
计算程序2()
Me.Dispatcher.BeginInvoke(New Action(Sub() t.Text = "进度消息2"))
System.Threading.Thread.Sleep(1000)
End Sub)
th.Start()
End Sub
[/quote]
差不多也就这样了,你看看实际上已经没几行代码了。 Private Sub Button_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim t As New TestClass
Me.DataContext = t
Dim th As New System.Threading.Thread(Sub()
计算程序1()
Me.Dispatcher.BeginInvoke(New Action(Sub() t.Text = "进度消息1"))
System.Threading.Thread.Sleep(1000)
计算程序2()
Me.Dispatcher.BeginInvoke(New Action(Sub() t.Text = "进度消息2"))
System.Threading.Thread.Sleep(1000)
End Sub)
th.Start()
End Sub
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="{Binding Text}" Width="75" Height="32" Margin="10"/>
<Button Content="测试" Click="Button_Click" Width="75" Height="32" Margin="10"/>
</StackPanel>
</Grid>
</Window>
Class MainWindow
Private Sub Button_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim t As New TestClass
Me.DataContext = t
Dim th As New System.Threading.Thread(Sub()
For index = 1 To 10
Dim i = index
Me.Dispatcher.BeginInvoke(New Action(Sub() t.Text = i.ToString()))
System.Threading.Thread.Sleep(1000)
Next
End Sub)
th.Start()
End Sub
End Class
Public Class TestClass
Implements System.ComponentModel.INotifyPropertyChanged
Private m_Text As String
Public Property Text() As String
Get
Return m_Text
End Get
Set(ByVal value As String)
m_Text = value
RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs("Text"))
End Set
End Property
Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
End Class
经测试通过,UI线程和其它线程的交互,可能真是个难点,不知道我这个例子能不能让你看懂。
另一个,UI线程的刷新其实是周期性的,你在数据线程中没有足够的延时的话,UI线程刷新上去的,只会是最后一个值。