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

查看:32
本文介绍了跨线程操作无效 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天全站免登陆