我有一個代碼,它有一個文本框和一個按鈕,當我按下按鈕時,代碼更新文本框,並且在單詞睡眠5秒後,被凍結 我試圖與代表,和線程但沒有任何工程 這是代表代碼:嘗試更新wpf中的文本框時UI會凍結
MainWindow.vb
Class MainWindow
Delegate Sub MySubDelegate(ByVal x As String)
Private m_engine As Engine
Public Sub New()
m_engine = New Engine(AddressOf WriteToLog)
InitializeComponent()
Me.DataContext = m_engine.GetViewModel()
End Sub
Public Sub WriteToLog(str As String)
Dim vv As ViewModel = CType(DataContext, ViewModel)
vv.Log = str
End Sub
Private Sub clicked(sender As Object, e As RoutedEventArgs)
m_engine.TimingRecord()
End Sub
End Class
Engine.vb
Private m_viewModel As New ViewModel
Private _msd As MainWindow.MySubDelegate
Public Sub New()
End Sub
Sub New(msd As MainWindow.MySubDelegate)
_msd = msd
End Sub
Public Function GetViewModel() As ViewModel
Return m_viewModel
End Function
Public Sub TimingRecord()
_msd("aaaaa")
SetText()
End Sub
Public Sub SetText()
Thread.Sleep(5000)
End Sub
viewModel.vb
Public Class ViewModel
Implements INotifyPropertyChanged
Private m_log As String
Public Property Log As String
Get
Return m_log
End Get
Set(value As String)
m_log = value
End Set
End Property
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(Optional ByVal propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
這與線程的代碼:
MainWindow.vb
Delegate Sub MySubDelegate(ByVal x As String)
Private m_engine As Engine
Public Sub New()
m_engine = New Engine(AddressOf WriteToLog)
InitializeComponent()
Me.DataContext = m_engine.GetViewModel()
End Sub
Public Sub WriteToLog(str As String)
Me.Dispatcher.Invoke(Sub() CType(DataContext, ViewModel).Log = str)
'Dim vv As ViewModel = CType(DataContext, ViewModel)
'vv.Log = str
End Sub
Private Sub clicked(sender As Object, e As RoutedEventArgs)
m_engine.TimingRecord()
End Sub
Engine.vb
Public Class Engine
Private m_viewModel As New ViewModel
Private m_thread As Thread
Private _msd As MainWindow.MySubDelegate
Public Sub New(msd As MainWindow.MySubDelegate)
_msd = msd
End Sub
Public Function GetViewModel() As ViewModel
Return m_viewModel
End Function
Public Sub TimingRecord()
m_thread = New Thread(AddressOf DoRecordThread)
m_thread.IsBackground = True
m_thread.Start("aa")
SetText()
End Sub
Public Sub SetText()
Thread.Sleep(5000)
End Sub
Private Sub DoRecordThread(str As String)
_msd(str)
'm_viewModel.Log = str
End Sub
End Class
視圖模型保持不變。我使用wpf,因此我將日誌綁定到文本框中,並使用簡單的代碼工作。
謝謝大家提前。
'SLEEP'導致你的線程好,睡吧。如果線程是你的用戶界面,那麼它就完全按照你所說的去做。 – Steve
你爲什麼要做'Thread.Sleep(5000)'? – Enigmativity
謝謝你的回覆,thread.sleep來代替一個很長的運行,從1到100000000,我把睡眠放在新的線程裏面,用戶界面沒有凍結,但是他的文本框沒有更新,你能幫我嗎 – Joe