Error: Must be in a Multithreaded
Apartment.
Home Product
Details Free 
Demo Pricing &
Ordering Related
Products Support About Us

Return to Documents list

I get the following error in my .NET application
"Must be in a multithreaded apartment. Apply MTAThread attribute or set System.Threading.ApartmentState to MTA"

Read on... there's an easy fix to this problem!

What does this mean?

This is one of those very few error messages that actually does describe the nature of the problem clearly, as well the instructions on how to fix the problem.

The error means that the apartment threading of your application is set to STA (Single Threaded Apartment) model which as this error states, is not the appropriate model to use.

When and why does this error occur?

    A good question! The error typically occurs when you use the OPCData.NET component within a .NET application, specifically when using Subscription Reads. Subscription Reads are when an event is raised each time a Tag's value changes.

    This error will occur when you try to call the RequestItem method within your application.

Fixing the Problem

    The fix for this problem is slightly different depending on which .NET language you are using... although the end-result is the same...

    C#

      C# developers have a slightly easier job than VB.NET developers. Simply locate your applications Entry-point "void main()" and then modify the attribute that precedes it:

      Before change...

      After change...

       [STAThread]
        static void Main()
        {
         Application.Run(new Form1());
        }

       [MTAThread]
        static void Main()
        {
         Application.Run(new Form1());
        }

    VB.NET

      VB.NET Winforms applications do not have an entry-point defined where the apartment-threading attribute is defined, instead the application is compiled as STA. The key to changing this is to perform the following steps:

    • Add a new Module to your application. If you already have a module defined, then you may wish to skip this step.
    • Add a PUBLIC SUB MAIN to the module and prefix it with the apartment-threading attribute as follows:
       
       Module Module1

        <MTAThread()> Public Sub main()
        End Sub

      End Module
    • Within the Main() sub, simply add the code to launch your Form.

Conclusion

    Changing the apartment threading your application uses will dictate whether or not your application can perform Subscription Reads.

    Questions or Feedback - send us an email.

 

Copyright Software Toolbox, Inc., 1996-2004, All Rights Reserved Worldwide.
148A East Charles Street, Matthews, North Carolina, USA 28105
Phone: 704-849-2773 or 1-888-665-3678 (US), Fax: 704-849-6388
sales@softwaretoolbox.com | support@softwaretoolbox.com