Can the DBConnection class be connected to by multiple STA threads in parallel?

Ao 21 Reputation points
2021-07-09T07:49:19.057+00:00

When multiple STA threads try to access the DB using the DBConncetion class, all but the first one will not return a Connet function.
When the program is stopped, the locked thread will get an exception saying "COM object that has been separated from its underlying RCW cannot be used."

Can the DBConncetion class only be used from an MTA thread?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,374 questions
{count} votes

Accepted answer
  1. Daniel Zhang-MSFT 9,611 Reputation points
    2021-07-13T01:26:48.58+00:00

    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful