大家知道WPF中多线程访问UI控件时会提示UI线程的数据不能直接被其他线程访问或者修改,该怎样来做呢?
分下面两种情况
1.WinForm程序
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 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和区别:BeginInvoke会立即返回,Invoke会等执行完后再返回。View Code
2.WPF程序
1)可以使用Dispatcher线程模型来修改
如果是窗体本身可使用类似如下的代码:
this.lblState.Dispatcher.Invoke(new Action(delegate{ this.lblState.Content = "状态:" + 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
新闻热点
疑难解答