0

Currently I have a global static MySqlConnection connection; which is shared across threads (bad, I know) but I lock while opening new connections or closing old ones and only do so if the thread is the first that has been created or the last that was left (I also determine this by a static int MySqlConnected).

Currently it gets mixed up for some reason, what is the problem with my setup?

3
  • What do you mean it gets mixed up? Could you explain what is your error? I have a feeling about it Commented May 30, 2013 at 11:42
  • @Steve the problem is that not the right query is executed for some reason, I write the values right before sending them to the query and they are completely different, I also tried running the query outside of a thread and it worked perfectly. Commented May 30, 2013 at 12:17
  • Look up .net connection pooling. You are doing this well wrong. Commented May 30, 2013 at 16:19

1 Answer 1

2

Why are you doing that anyway?

The .NET runtime is already quite efficient at keeping a pool of connections and re-using them as needed transparently in a safe and hassle-free way. It looks to me like you're trying to accomplish something that's already provided by the framework. When you need to execute a query, just open a new connection and use it. The runtime will take care of all the rest for you.

Additionally, using threads plus static variables is a great recipe for trouble, resulting in code that often fails in subtle, non-obvious ways. You seem to be implementing some kind of home-grown locking mechanism which is very easy to get wrong. So unless you're very experienced with multithreaded scenarios, I'd stay away from this kind of thing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.