【问题标题】:Error: The current thread must be in Single Thread Apartment错误:当前线程必须在单线程单元中
【发布时间】:2017-03-31 03:02:23
【问题描述】:

每当我尝试打开 Openfiledialog 时都会出现此错误:

在进行 OLE 调用之前,当前线程必须处于单线程单元 (STA) 模式。确保您的 Main 函数被标记为 STAThreadAttribute。仅当将调试器附加到进程时才会触发此异常。

我的代码:

    Dim ofg As New OpenFileDialog
    Dim lvp As New ListViewItem

    ofg.Multiselect = True
    ofg.Filter = "All Files|*.*"
    Statue.Text = "Loading..."

    If ofg.ShowDialog = Windows.Forms.DialogResult.OK Then
        For Each File As String In ofg.SafeFileNames

            Dim hInst As IntPtr = Marshal.GetHINSTANCE([Assembly].GetExecutingAssembly.GetModules()(0))
            Dim iIcon As Int32 = 0
            Dim hIcon As IntPtr

            hIcon = ExtractAssociatedIcon(hInst, File, iIcon)
            ico = Icon.FromHandle(hIcon)
            icondufile = ico.ToBitmap
            Img.Images.Add(icondufile)
            Dim C_File As New IO.FileInfo(File)

            Dim ItemFile As ListViewItem = New ListViewItem(C_File.Name)
            lvp = Files_List.Items.Add(ItemFile)
            lvp.SubItems.Add(MD5Checksum(File))
            lvp.SubItems.Add(hash_generator("sha1", File))
            lvp.SubItems.Add(hash_generator("sha256", File))
            lvp.SubItems.Add(GetCRC32(File))
            lvp.SubItems.Add(hash_generator("sha384", File))
            lvp.SubItems.Add(hash_generator("sha512", File))
            lvp.SubItems.Add(C_File.FullName)
            lvp.SubItems.Add(C_File.Extension)
            lvp.StateImageIndex = lvp.Index

            ItemFile = Nothing

        Next

  Private Sub AddFilesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddFilesToolStripMenuItem.Click
    trd = New Threading.Thread(AddressOf AddFiles)
    trd.IsBackground = True
    trd.Start()
    Timer_AddFiles.Start()
End Sub

【问题讨论】:

  • 它似乎在告诉你该怎么做

标签: vb.net multithreading


【解决方案1】:

您可以使用 Form Invoke 方法或将 Thread Apartment 设置为:

Dim ItemFile As ListViewItem
Private Function Init()  
 trd = New Threading.Thread(AddressOf AddFiles)
 trd.IsBackground = True
 trd.SetApartmentState(Threading.ApartmentState.STA) ''You can set MTA or STA
 trd.Start(ItemFile)
End Function
Private Sub DoFormUiBased()
    '' Add your code here
End Sub
Private Function AddFiles(ByVal Argument As Object)
    Me.Invoke(New MethodInvoker(AddressOf DoFormUiBased))
End Function

【讨论】:

  • 在多线程中,不要忘记使用ThreadSafe或threadPool,因为可能会出现Cross Thread。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多