大家知道WPF中多線程訪問UI控件時會提示UI線程的數據不能直接被其他線程訪問或者修改,該怎樣來做呢?
分下面兩種情況
1.WinForm程序
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017012018584724.gif)
![]()
1
2 1)第一種方法,使用委托:
3 private delegate void SetTextCallback(string text);
4 private void SetText(string text)
5 {
6 // InvokeRequired需要比較調用線程ID和創建線程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 else
14 {
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(delegate
24 {
25 this.txt_Name.Text = obj;
26 }));
27 }
28 else
29 {
30 this.txt_Name.Text = obj;
31 }
32 }
33 這裡說一下BeginInvoke和Invoke和區別:BeginInvoke會立即返回,Invoke會等執行完後再返回。
View Code
2.WPF程序
1)可以使用Dispatcher線程模型來修改
如果是窗體本身可使用類似如下的代碼:
this.lblState.Dispatcher.Invoke(new Action(delegate
{
this.lblState.Content = "狀態:" + this._statusText;
}));
那麼假如是在一個公共類中彈出一個窗口、播放聲音等呢?這裡我們可以使用: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();
}
}));