none
Current thread must be set to single thread apartment (STA) mode before OLE

    Question

  • I recently updated a simple program that uses a filedialog control to locate  
      
    a file.  When I try and run the following code I get this error:  
      
    Current thread must be set to single thread apartment (STA) mode before OLE  
      
    calls can be made. Ensure that your Main function has STAThreadAttribute  
      
    marked on it. This exception is only raised if a debugger is attached to the  
      
    process.  
      
    Here is the code  
      
    this.openFileDialog1.FileName = this.txtCompilePath.Text;  
      
    DialogResult result = openFileDialog1.ShowDialog(this);  
      
    if (openFileDialog1.ShowDialog() == DialogResult.OK)  
      
    {  
      
    this.txtCompilePath.Text = openFileDialog1.FileName;  
      
    }
    
    Monday, April 09, 2007 1:33 PM

Answers

  •  

    Add the STAThreadAttribute attribute on the Main method. This attribute is required if your program access OLE related functions, like Clipboard class does.

     

    C#

    [STAThread]

    static void Main(string[] args)

    {

    }

     

    Visual Basic

    <STAThread()> _

    Shared Sub Main(args As String())

     

    End Sub

     

    Monday, April 09, 2007 2:11 PM

All replies

  •  

    Add the STAThreadAttribute attribute on the Main method. This attribute is required if your program access OLE related functions, like Clipboard class does.

     

    C#

    [STAThread]

    static void Main(string[] args)

    {

    }

     

    Visual Basic

    <STAThread()> _

    Shared Sub Main(args As String())

     

    End Sub

     

    Monday, April 09, 2007 2:11 PM
  • I was having same problem so, following solution posted at link below, I simply deleted all dlls (there were a few old ones) in my output folder then rebuilt it and it worked.

     

    http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.windowsforms/topic36723.aspx

    Monday, October 15, 2007 7:43 PM
  • My main function already had [STAThread] above it, but the URL provided in the previous message was what I needed.  There was just an old DLL in my bin\debug folder that had to be deleted. 

    Thursday, January 10, 2008 4:46 AM
  • I get the same error aswel.

     

    [STATThread] is already on top of the main method

     

    Which "old DLL" are you referring to?

     

    Thanks

     

    EThan

     

    Sunday, June 08, 2008 5:57 PM
  • Hi,

    I am using a clipboard function in my webpage.

    It gives me the same error

    I dont have as such any main fnction in my program.

    I tried placing [STATThread] before the event handler of the button click event.

    On this button click text on the webpage has to be coped to clipboard

     

    I need help regarding this

    Tuesday, June 24, 2008 12:21 PM
  • After I deleted my used DLL files, everything is going fine.

    Saturday, July 19, 2008 8:16 PM
  • Hi, my project is a C# .NET website, so it doesn't have a main(). How do I apply the advice to set STA mode if there's no main() entry point?

     

    Thanks,

     

    - Steve

     

    Tuesday, August 26, 2008 2:07 AM
  • Ditto with Steve and t-VKS.
    If anyone knows the solution, please post.

    Thanks,
    Phil
    Friday, August 29, 2008 3:59 PM
  • Ditto with Steve and t-VKS.
    If anyone knows the solution, please post.

    Thanks,
    Phil

    Hi I am also facing the same isue can anyone help me out
    Friday, April 03, 2009 11:35 AM
  • RESPUESTA AL PROBLEMA DE LA EXCEPCIÓN

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

    SOLUCIÓN

    [

     

    STAThread] //MUY NECESARIO PARA EJECUTAR LOS métodos OLE y COM 

    private void MetodoCualquiera() //no necesariamente el main, solo el que llama al hilo que llama al dialog

    {

    Thread

    hilo = 

     

    hilo = 

    hilo = 

     

    new Thread(MetodoALlamar);

    hilo.IsBackground =

    true;

    hilo.SetApartmentState(

    ApartmentState.STA); //evitamos la excepción, no se bién porque

     

     

    hilo.Start(IVAVentas);

    }

    medio confuso pero ahi está

    Thursday, September 17, 2009 11:04 PM
  • I am having this error as well.  I have the [STATThread] about the main function.  I had an older version of Visual Studio on my PC before running this app.  However, I have now completely reinstalled Visual Studio 2008.  It still does not work.  Please advise.

    Thursday, March 04, 2010 2:31 PM
  • I have followed the sugestions above, but no matter what I do, I still get this same error.

    The code I am using to save a file is the same code I have always used. Now, in VB 2008, I get this error and I cannot get around it. I would appreciate any advise to correct this. Thank you.

                With SaveFileDialog1
                    .DefaultExt = ".xls"
                    .Filter = "Excel - Worksheet (*.xls)|*.xls|Text Document (*.csv)|*.csv|Word Documents (*.doc)|*.doc|Rich Text Format (*.rtf)|*.rtf|DataBase Format (*.dbf)|*.dbf|All files (*.*)|*.*"
                    .FilterIndex = 1
                    .RestoreDirectory = True
                    .InitialDirectory = "C:\"
                    If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then The code fails on this line!
                        Select Case Microsoft.VisualBasic.Right(.FileName, 3).ToLower
                            Case "xls"
                                _rsReport.Destination = CStr(Destination.ExcelWorksheet)
                            Case "csv"
                                _rsReport.Destination = CStr(Destination.TextDataFile)
                            Case "doc"
                                _rsReport.Destination = CStr(Destination.WordMergeFile)
                            Case "rtf"
                                _rsReport.Destination = CStr(Destination.RTFFile)
                            Case "dbf"
                                _rsReport.Destination = CStr(Destination.DBFFile)
                        End Select
                    End If '.ShowDialog
                End With
    Wednesday, March 17, 2010 8:53 PM
  • **************** working ***********************
    Hi All,



    After trying for couple of hrs, I got the solution



    using System.Threading;

       protected void Button1_Click(object sender, EventArgs e)
        {
            
            Thread newThread = new Thread(new ThreadStart(ThreadMethod));
            newThread.SetApartmentState(ApartmentState.STA);
            newThread.Start();     
            
        }

    static void ThreadMethod()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.ShowDialog();
            MessageBox.Show(dlg.FileName);
        }
    • Proposed as answer by Killer1390 Wednesday, November 24, 2010 2:18 AM
    Tuesday, July 27, 2010 6:56 PM
  • Gracias Juanico. Tu respuesta fue la solucion a mi problema. Estaba iniciando un reproductor de reportes crystal en un hilo me daba el error enunciado en el encabezado cuando queria usar el reproductor para exportar reportes en windows 7 (en windows xp funcionaba sin problemas). Para solucionarlo basto con agregarle oThread.SetApartmentState(ApartmentState.STA).

     

    Thanks Juanico. Your answer helped me to fix my problem. I was using a thread to start a crystal reports viewer and I was having the above mentioned error when trying to use the viewer to export reports in windows 7 (in windows XP worked ok). To avoid the issue I just added the SetApartmentState(ApartmentState.STA) statement to my code

     

    Dim oThread As New Thread(AddressOf DisplayThreadReport)

    oThread.SetApartmentState(ApartmentState.STA)

    oThread.Start()

    Monday, January 31, 2011 3:26 PM
  • thanx !!!!it realy works fectivelyy,,,
    Sunday, March 13, 2011 11:10 PM
  • Hi Steve,

    Have you solved this issue :

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

    I am developing class library using windows applicaton, I did n’t have any main function then how to solve this issue

     

    Thanks


    kavitha
    Tuesday, November 22, 2011 5:43 AM
  • thank u thank u thank u and thank u.... this really solved my problem. thank u once again
    Wednesday, June 13, 2012 3:24 AM
  • Thank you Bharat Mehndiratta USC and Guillermo Pedraza for your amazing answers.  I know it has been awhile since you answered but I have had this problem with my VS 2008 application where I'm trying to copy my gridview onto the clipboard.  It gives me the error stated above.  I want to use your answer but when I try to fill DisplayThreadReport it overloads the first thread.  What do you put in there for a report and do you put it up in the public class or within the button click event?  Any help would be appreciated. This is my second straight day looking for a solution!

    Thanks!

    Tuesday, July 03, 2012 6:35 PM
  • RESPUESTA AL PROBLEMA DE LA EXCEPCIÓN

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

    SOLUCIÓN

    [

     

    STAThread] //MUY NECESARIO PARA EJECUTAR LOS métodos OLE y COM 

    private void MetodoCualquiera() //no necesariamente el main, solo el que llama al hilo que llama al dialog

    {

    Thread

    hilo = 

     

    hilo = 

    hilo = 

     

    new Thread(MetodoALlamar);

    hilo.IsBackground =

    true;

    hilo.SetApartmentState(

    ApartmentState.STA); //evitamos la excepción, no se bién porque

     

     

    hilo.Start(IVAVentas);

    }

    medio confuso pero ahi está

    This pretty much cleared up my error, at least it didn't work before I implemented it.

            [STAThread] 
            private void btnTextReadReports_Click(object sender, EventArgs e)
            {
                Thread t = new Thread(WriteY);          // Kick off a new thread
                t.IsBackground = true;
                t.SetApartmentState(ApartmentState.STA);
                t.Start();                               // running WriteY()
            }

    Thanks a bunch.

     
    • Edited by Daniel9d8 Tuesday, July 24, 2012 9:22 PM
    Tuesday, July 24, 2012 9:22 PM
  • If adding 

    C#

    [STAThread] attribute in the main does not work, then delete all references for that project and then add those references again.  This worked for me!


    Mike

    Wednesday, August 01, 2012 8:46 PM
  • I had the same problem, but went with a complete different route that seems to work just as well. I used a invoke method from another object on the form as FolderBrowserDialog doesn't have an invoke method and it calls it on the necessary thread without any problems.
    Public Sub BrowseFolderForDirectory()
        If Me.ListView1.InvokeRequired Then 'any other object on that form as FolderBrowserDialog doesn't have any invoke method
            Me.ListView1.Invoke(New MethodInvoker(AddressOf BrowseFolderForDirectory))
        Else
            With FolderBrowserDialog1
                If .ShowDialog = DialogResult.OK Then
                    'code here
                End If
            End With
        End If
    End Sub
    

    Sunday, August 12, 2012 6:51 AM
  • Wow deleteing all dll's in project reference did solve my Thread Exception problem.

    That was unbelievable. I could have never imagined those dll's are causing this problem.

    Thanks!!!

    Friday, November 02, 2012 8:53 PM