简单介绍.Net3.0 中跨线程访问控件

这两天用WPF做一个项目的UI部分时,发现跨线程地访问了UI控件,自然地报异常了。当时找了半天也没在控件中找到InvokeRequired属性和Invoke方法,郁闷之极.....最后发现在.net3.0中,这有所改变了。

  替代InvokeRequired的方法是DispatcherObject.CheckAccess()或DispatcherObject.VerifyAccess()方法,用于指示当前线程是否可以直接访问控件。

  替代Invoke的方法是DispatcherObject.Dispatcher.BeginInvoke(...)方法。

  参考代码:

 

  // Uses the DispatcherObject.CheckAccess method to determine if 
  // the calling thread has access to the thread the UI object is on 
  private void TryToUpdateButtonCheckAccess(object uiObject) 
  { 
   Button theButton = uiObject as Button; 
   
   if (theButton != null) 
   { 
   // Checking if this thread has access to the object 
   if(theButton.CheckAccess()) 
   { 
   // This thread has access so it can update the UI thread 
   UpdateButtonUI(theButton); 
   } 
   else 
   { 
   // This thread does not have access to the UI thread 
   // Pushing update method on the Dispatcher of the UI thread 
   theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal, 
   new UpdateUIDelegate(UpdateButtonUI), theButton); 
   } 
   } 
  }

转载于:https://www.cnblogs.com/aspnetjia/p/5148342.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在码农的生活,很多级码农都有这样的经历,会被一个小小的技术问题拦住,然后进度跟不上了,被老板XXXX一大通了。心情不爽了。 好吧,这个曾经是我遇到拦路虎之一。但事实上不是什么大技术。技术就是一层纸,破了就破了。 这是一个关于如何窗体操作控件或过程的一个例子。比如,你想用窗体A的按键来执行窗体B的文本框变色。 Imports System Imports System.Threading Imports System.Text Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load CheckForIllegalCrossThreadCalls = False '不写这行,会出错,不允许线程的数据写到TextBox1.Text 去。 Form2.Show() End Sub Private Sub form1_FormClosing(sender As Object, e As EventArgs) Handles Me.FormClosing ' If runThread.IsAlive = True Then runThread.Abort() End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click '用的是委托方式 Me.Invoke(New MethodInvoker(AddressOf THREAD2)) End Sub Private Sub THREAD2() Static j As Integer j = j + 1 TextBox1.Text = " 这是 [线程] 操作" & vbCrLf & _ " Button2被点了: " & j & " 次" & vbCrLf & "要求是from2.textbox.text= textbox1.text 。[问题]但为什么不能成功显示呢?" End Sub Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged Form2.TextBox1.Text = TextBox1.Text End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click Static j As Integer j = j + 1 TextBox1.Text = " 这是 [非线程] 操作" & vbCrLf & _ "Button3 点击了: " & j & " 次" & vbCrLf & _ "要求是from2.textbox.text= textbox1.text, 可以成功显示,这个是对的。" End Sub End Class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值