大家知道WPF中多線程訪問UI控件時會提示UI線程的數(shù)據(jù)不能直接被其他線程訪問或者修改,該怎樣來做呢?
分下面兩種情況
1.WinForm程序

1 2 1)第一種方法,使用委托: 3 PRivate delegate void SetTextCallback(string text); 4 private void SetText(string text) 5 { 6 // InvokeRequired需要比較調(diào)用線程ID和創(chuàng)建線程ID 7 // 如果它們不相同則返回true 8 if (this.txt_Name.InvokeRequired) 9 {10 SetTextCallback d = new SetTextCallback(SetText);11 this.Invoke(d, new object[] { text });12 }13 else14 {15 this.txt_Name.Text = text;16 }17 }18 2)第二種方法,使用匿名委托19 private void SetText(Object obj)20 {21 if (this.InvokeRequired)22 {23 this.Invoke(new MethodInvoker(delegate24 {25 this.txt_Name.Text = obj;26 }));27 }28 else29 {30 this.txt_Name.Text = obj;31 }32 }33 這里說一下BeginInvoke和Invoke和區(qū)別:BeginInvoke會立即返回,Invoke會等執(zhí)行完后再返回。View Code
2.WPF程序
1)可以使用Dispatcher線程模型來修改
如果是窗體本身可使用類似如下的代碼:

this.lblState.Dispatcher.Invoke(new Action(delegate{ this.lblState.Content = "狀態(tài):" + this._statusText;}));View Code那么假如是在一個公共類中彈出一個窗口、播放聲音等呢?這里我們可以使用:System.Windows.application.Current.Dispatcher,如下所示

System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => { if (path.EndsWith(".mp3") || path.EndsWith(".wma") || path.EndsWith(".wav")) { _player.Open(new Uri(path)); _player.Play(); } }));View Code新聞熱點
疑難解答