Is SqlConnection / SqlCommand thread safe?

丶灬走出姿态 提交于 2019-11-29 07:34:27

Am I interpreting this correctly in thinking it means that MS does not guarantee that SqlCommand works in a multi threaded scenario?

It works fine in a multi-threaded scenario as long as you use it correctly.

If several threads try to use the SAME SqlCommand, what do you think will happen? How could it possibly work?

but if different threads using different connections issue different commands to the same database, there is no problem.

The notes about thread safety on MSDN are really broken and badly worded, and must be written by someone who didn't know what thread safety is.

What they're trying to say with that message (which is tacked onto 99.9% of the classes and functions documented on MSDN) is that "Any static method of this type can be safely called concurrently by multiple threads. Any instance members on the same instance is not guaranteed to be safe if invoked concurrently by multiple threads, but accessing the same member on different objects is perfectly fine."

I'm not 100% sure what you're trying to do simultaneously with SqlCommand, but whatever the internal thread-safety, you'll surely have problems purely because using the SqlCommand requires it to maintain state, e.g.

SqlCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "......";
cmd.Parameters.Add(.....);
cmd.ExecuteNonQuery();

If you're trying to share the same command through multiple threads, you'd have to lock something while you were using it.

As far as SqlConnection goes, it will only allow you to have a single query open at a time, so if you're using DataReaders, you'd again have to lock something. Using multiple connections/commands is essential if you want to run multiple things the same time.

I'm also not sure what you mean when you say WCF has no shared application state - this is not necessarily true, it will depend on how you are hosting your WCF application. If it is a WCF service hosted under IIS with aspNetCompatibilityEnabled="true" set, you still have the Application object you would get in a web site. There are other options if you're not using aspNetCompatibility as well.

just use connection and command from knly one thread and dont care of app level thread issue on those. sql server is good enough to handle concurrency for you with no need to lock in your code. .Net connection pool is also there to retrieve valid connections fast.

I am not saying the whole WCF layer you make should not care of threads, but its DAL has to work relying on db locks not .net locks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!