跨线程操作无效VB.NET [英] Cross-Thread operation not valid VB.NET

查看:207
本文介绍了跨线程操作无效VB.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾了整个站点,发现与该主题有关的问题是C#(我维护的应用程序是用VB.NET编写的),因此如果我忽略了一个,我深表歉意.

I looked around the site and the questions I found relating to this subject were for C# (the application that I am maintaining is written in VB.NET), so I apologize if I overlooked one.

在这里我正在调用线程:

Here is where I am calling my thread:

Private Sub saveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles saveBtn.Click
    If Not LoadedFilePath = String.Empty Then
        Dim oTrd = New Threading.Thread(AddressOf SaveData)
        oTrd.Start()
    End If
End Sub

这是方法:

Private Sub SaveData()
    SaveData(LoadedFilePath)
End Sub
Private Sub SaveData(ByVal filepath As String)
    If InvokeRequired Then
        Me.Invoke(New MethodInvoker(AddressOf SaveData))
    End If
    Try
        Me.Cursor = Cursors.WaitCursor
        Dim oSettings As New SettingsClass(filepath)
        Dim oEnc As New AES
        With oSettings
            //' Code removed for brevity
        End With
        oEnc = Nothing
        oSettings.SaveSettings()
        savedLbl.Visible = True
        If SavedTimeout IsNot Nothing Then
            Try
                SavedTimeout.StopEvent()
            Catch
            End Try
        End If
        SavedTimeout = New TimedEvent(Now.AddSeconds(5))
        SavedTimeout.StartEvent()
        Me.Cursor = Cursors.Default
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

保存功能可以正常工作,但是当程序尝试将光标切换回默认值时,出现了跨线程错误.我该怎么做才能解决此问题?

The save function works just fine, but I get the cross-thread error when the program tries to switch the cursor back to default. What can I do to fix this problem?

推荐答案

您在所有者(GUI)线程中调用方法的方式是错误的.如果需要调用,则不应执行该方法中的其余代码.如果这样做,您将同时在GUI线程和后台线程中执行它,并且当您尝试从后台线程访问GUI元素时,您会遇到跨线程错误.

Your way of invoking the method in the owner (GUI) thread is wrong. If invocation is required, you should not execute the rest of the code in the method. If you do, you will be executing it both in the GUI thread and the background thread, and when you try to access the GUI elements from the background thread you get the cross-thread error.

调用应如下所示:

Private Sub SaveData(ByVal filepath As String)
   If InvokeRequired Then
      Me.Invoke(New MethodInvoker(AddressOf SaveData))
   Else
      ... the actual code
   End If
End Sub

但是当必须在GUI线程中调用自身时,为什么要在后台线程中启动该方法呢?

But why are you starting the method in a background thread, when it has to invoke itself in the GUI thread anyway?

这篇关于跨线程操作无效VB.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆