首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >VB.NET跨线程操作无效

VB.NET跨线程操作无效
EN

Stack Overflow用户
提问于 2011-09-04 07:55:06
回答 2查看 3.5K关注 0票数 0

我有一个循环(BackgroundWorker),它非常频繁地更改图片框的位置,但我得到了一个错误-

代码语言:javascript
复制
Cross-thread operation not valid: Control 'box1' accessed from a thread other than the
  thread it was created on.

我一点也不明白,所以我希望有人能帮助我解决这个问题。

代码:

代码语言:javascript
复制
  box1.Location = New Point(posx, posy)
EN

回答 2

Stack Overflow用户

发布于 2011-09-04 08:18:07

当您尝试从创建控制的线程以外的线程访问控制时,将引发此异常。

要解决此问题,您需要使用控件的InvokeRequired属性来查看是否需要更新,而要更新控件,则需要使用委托。我认为您需要在backgroundWorker_DoWork方法中执行此操作

代码语言:javascript
复制
Private Delegate Sub UpdatePictureBoxDelegate(Point p)

Dim del As New UpdatePictureBoxDelegate(AddressOf UpdatePictureBox)

Private Sub UpdatePictureBox(Point p)
    If pictureBoxVariable.InvokeRequired Then

        Dim del As New UpdatePictureBoxDelegate(AddressOf UpdatePictureBox)
        pictureBoxVariable.Invoke(del, New Object() {p})
    Else
        ' this is UI thread     
    End If
End Sub
票数 2
EN

Stack Overflow用户

发布于 2015-04-13 23:32:09

对于遇到此错误的其他人:

尝试dispatcher对象:MSDN

我的代码:

代码语言:javascript
复制
Private _dispatcher As Dispatcher

Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
    _dispatcher = Dispatcher.CurrentDispatcher
End Sub

Private Sub otherFunction()
    ' Place where you want to make the cross thread call
   _dispatcher.BeginInvoke(Sub() ThreadSafe())
End Sub

Private Sub ThreadSafe()
    ' here you can make the required calls
End Sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7296564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档