Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sql Exception in 2nd thread

Status
Not open for further replies.

raghu75

Programmer
Nov 21, 2000
66
IN
Hi,
I am debugging an application which spawns 2 threads in C#.
Both the threads try & get sql connection to a DB and insert some records in to DB.
The Problem is when I run the application the second thread is throwing an exception which states that the SqlConnection is already Open.But the First thread has closed its connection by commit/rollback.Hence there are no open connections!!!
I am surprised why it behaving like this while Running the application...any inputs appreciated


rgds.
raghu
 
Recall that .NET is a garbage-collected language. Even though the first thread has closed it's connection, it might still be open until a GC cycle runs.

You should:
1) Call the Dispose() method on your connection object after closing it (will probably work)
-or-
2) Use two connections
-or-
3) Do something else to solve the problem ;-)

If you opt to continue sharing a connection -- make sure you have some synchronization code in there to prevent both threads from attempting to use it at the same time.

Chip H.
 
Hi,
I am opening two different connections in these two threads.
This is working as expected in debug mode.When I run the application then the second thread throws an exception saying the connection is already open...

raghu
 
Hmmmm.

I haven't run into this. I would suspect the ADO.NET connection pooling is behind it. I wonder if you can check the .State property of your connection object before calling the .Open method.

Chip H.
 
That's a good idea. Check the state, and if its open, do nothing.

It is weird though. Try one connection with Windows authentication, and the other with SQL Auth. if you can. I'd be interested in seeing what happens.
 
Hi,
I was debugging this and found the following...
The threads are asynchronous.i.e. they are created using begininvoke & endinvoke in C#.
I am creating new sqlconnection in every thread and using it.This works fine for the first thread.But the second thread and the later threads run on the first thread itself...thereby giving exception for my sqlconnection.. which is already open???
I cant understand why the remaining threads are running on the back of the first thread....?

Any Help ???


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top