Hi TakuyaYamauchi-1944,
Connections, commands, and readers are not thread-safe. Therefore, if you intend to run this code in multiple threads, each thread needs to create its own connections, commands, and readers. And if your application is multi-threaded, you need to use it in each The COM object is instantiated in the thread.
The STA model is used for non-thread-safe COM objects. If the COM object can handle its own synchronization, you can use the MTA model, which allows multiple threads to interact with the object without marshalling calls.
Here is a thread to help you understand better.
Best Regards,
Daniel Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Hi @Ao ,
Yes, you cannot use the same connection object in all threads. Give each thread a dedicated database connection.
More information about STAThread, please refer to this thread.
Best Regards,
Daniel Zhang
Hi @Daniel Zhang-MSFT ,
I thought I was using a different connection object in every thread.
But does that mean that the same connection object is actually being used?
Our program, written in C#, creates a connection for each STA thread as follows.
Then we use this connection in the same thread and Dispose it after it is used.
So when I process from these multiple STA threads, _connection.Open(); doesn't come back.
Does this mean that multiple connections can't be used from multiple threads?
Hi @Ao ,
>>But does that mean that the same connection object is actually being used?
Based on your code, you create a new OleDbConnection connection for each STA thread.
So a new connection object is used in each thread.
>>when I process from these multiple STA threads, _connection.Open(); doesn't come back.
STA (Single Threaded Apartment): Only one thread will interact with your code at a time.
So you need to use MTA (Multithreaded Apartment) where many threads can run at the same time.
Best Regards,
Daniel Zhang
Hi @Daniel Zhang-MSFT ,
Thank you very much for your answer.
I now understand that I need to use MTA to handle COM such as DbConnection in a multi-threaded environment.
Thank you very much for your help.
Best Regards,
Takuya Yamauchi
Sign in to comment