Must be in a multithreaded apartment Error in .NET Languages
"Must be in a multithreaded apartment. Apply MTAThread attribute or set System.Threading.ApartmentState to MTA"
This information can be accessed in document-form here.
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 OPC Data Client 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 application's Entry-point void main() and then modify the attribute that precedes it:
| Before change... | After change... |
[STAThread] |
[MTAThread] |
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 mainto 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.