Skip to content

Dealing with Execute-Assembly Entrypoint errors and Single Threaded Apartments in unmanaged code.

If you ever wrote C# tools and wanted to execute them using Execute-Assembly, chances are that you have encountered entrypoint errors. They look like this:

After discussing this issue with @rastamouse I’ve come to the conclusion that this issue occurs 99.9% of the time because the assembly is throwing an unhandled error. You can fix this by wrapping your entire code in one massive try catch block or start writing some nice error handling in your assembly 🙂

Single Threaded Apartments

If you ever wanted to create an assembly that does OLE/COM calls, you might have noticed that you’ll need to have a STA thread in your assembly. This is usually done like so:

        [STAThread]
        public static void Main()
        {
            Console.Writeline("Hello from STA!");
        }

This works perfectly in managed conditions, but I’ve noticed that this approach does NOT work when using Execute-Assembly functionality. The workaround for this is to create a new STAThread from your main method, instead of trying to make your main single threaded:

public static void Main()
          {
            Thread staThread = new Thread(() => SomeFunction());
	    staThread.SetApartmentState(ApartmentState.STA);
            staThread.Start();
           }

public static void SomeFunction() 
{
}

or alternatively, if your function isn’t void but actually returns something:

public static void Main()
          {
            String GiveMeThoseJuicyReturnValues = "";
            String input = "Hello World!";
            Thread staThread = new Thread(() => {
            GiveMeThoseJuicyReturnValues = SomeFunction(input);
            });
	    staThread.SetApartmentState(ApartmentState.STA);
            staThread.Start();
            Console.WriteLine(GiveMeThoseJuicyReturnValues);
           }

public static String SomeFunction(String someinput) 
{
   return someinput;
}

Pro tip: Do not attempt to use thread.sleep or any other timed interruption techniques in your newly created thread. It seems that the thread is limited in time suspended to 1 second, which isn’t very useful, You’ll have to implement your timing logic in your main function (original thread).

Published inTips & Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *