简体   繁体   中英

Is the .net DbProviderFactory thread safe?

I'm refactoring some old code based on DbProviderFactory to take advantage of connection pooling, but I ran into a simple question: Is the object returned by DbProviderFactories.GetFactory() thread-safe?

The code now is this:

DbProviderFactory factory = DbProviderFactories.GetFactory("Provider String from config");
var connection = factory.CreateConnection();
connection.ConnectionString = "connection string from config";

etc, etc. But this is done once PER THREAD. Obviously not what I'd want.

I wondered if I can use the "factory" object everywhere? Can I create multiple connections in different threads from the same DbProviderFactory object? Can I create DbAdapter classes, again, from the same factory?

As stupid as it is, the MSDN doc for even the concrete sub-classes don't say if you can do this. For example the msdn doc for SqlClientFactory for the CreateDataAdapter() method doesn't say if it's thread-safe or not. A few different guides on the internet have about just opening an instance of SqlConnection and it'll do thread-pooling, which is fine, but if you then do this:

SqlConnection connection = new SqlConnection("my connection string);
DbDataAdapter adapt = DbProviderFactories.GetFactory(connection).CreateDataAdapter();

Is that thread-safe? How many of those factories exist? What does that GetFactory method there return across threads? Always the same object? Or not? My existing code that I'm modifying uses DbDataAdapter s heavily, so I don't really want to change all of that too.

So is it thread-safe to take the factory and use it from multiple threads?

MSDN says:-

Thread Safety:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM