错误:当前线程必须位于单线程单元中

时间:2017-03-31 03:02:23

标签: vb.net multithreading

每当我尝试打开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

1 个答案:

答案 0 :(得分:0)

您可以使用表单调用方法或将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