VB.NET 08 OpenFileDialog in 2nd Thread throws ThreadStateException

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Wagz
    New Member
    • Feb 2008
    • 11

    VB.NET 08 OpenFileDialog in 2nd Thread throws ThreadStateException

    Hi,

    I have a main form which creates a thread. I want to make this child thread open a OpenFileDialog, but whenever I try to do this I get:

    ThreadStateExce ption.

    Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttrib ute marked on it. This exception is only raised if a debugger is attached to the process.


    Clearly it doesn't like it when I show an OpenFileDialog box from a secondary thread, but is there any way around this?

    Here's some sample code that illustrates the problem:

    Code:
    Public Class Form1
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            trd = New Threading.Thread(AddressOf trdTask)
            trd.IsBackground = True
            trd.Start()
        End Sub
    
        Private trd As Threading.Thread
        Private Sub trdTask()
            Dim file As OpenFileDialog = New OpenFileDialog
            file.ShowDialog()
        End Sub
    End Class

    Thanks,

    Wagz
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Did you follow its directions?
    Is your program running with STAThread and not MTAThread(or whatever).
    Did you confirm that the exception is only thrown when the debugger is attached?
    Why do you need it runing on another thread? I would think that generally the user interactive stuff would be run on the same thread. (ie: the GUI and any interactive IO), while anything that needs to be "still going on" would be done on other threads.

    Comment

    • jhaxo
      New Member
      • Dec 2007
      • 57

      #3
      Do you intend this file dialog to be accessible associated with a main ui?

      Windows does not much like any threads other than the ui thread touching its gui's and will throw an exception if you try it. That is really a good thing, previous versions of windows let you try to do it anyway and only later would problems show up.

      Try having the thread invoke a delegate in the ui that pops up this dialog?

      Comment

      Working...