esalem
esalem

Reputation: 19

Calling static method from external application

I have the following static function that exports to be called from external application

[DllExport("Initialize", CallingConvention = CallingConvention.StdCall)] 
public static void OnStartUp1( )
{
    try
    {
        a = new Indicator();
        a.Init();

    }
    catch (Exception e)
    {
        MessageBox.Show(e.ToString());

    }
}

when I used and call this method from .NET another application it is working well but when I call it from the external application that I build this function for it is return the following exception :

System.InvalidOperationException: DragDrop registration did not succeed. ---> 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.

Upvotes: 0

Views: 249

Answers (1)

CodingYoshi
CodingYoshi

Reputation: 27039

You need to match the same apartment. The error indicates that it must be called from an application with the same apartment (Single Threaded Apartment or STA). Therefore, your calling application must be STA.

To make it STA, you need the [STAThread] attribute on your main method.

This has to do with COM. Some COM components can only be accessed by a single thread so they are hosted in an STA. Some are made thread-safe and be accessed by multiple threads so they are hosted in Multi Threaded Apartment (MTA). When you are calling these COM components you must match that apartment.

You will notice windows forms applications will have main method like this:

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
}

Most like the .NET application, with which it is working and you do not get that error, has this [STAThread] attribute on its main method.

Upvotes: 1

Related Questions