开发者

Global SQL connection in background

I am trying to create a small Windows Forms App with .Net 4.0

Part of my program needs to connect to to a database but when I do the following:

SqlConnection conn = new SqlConnection(connectionString);

try
{
    conn.Open();
} 

....

The whole program kind of just hangs until the connection is made. What I want to do, is be able to make/open this connection, I suppose, in the background. So the program will still respond to button clicks etc.

Also, how do I make this single connection available globally to开发者_Go百科 my program?

Thanks in advance.


You should address the problem of why it takes so long to get a connection. It sounds more like you want to treat the symptoms which is that it hangs your application.

How do I make this single connection available globally to my program?

This is bad practice. Connections to databases should be kept open for the shortest duration possible. Acquire a connection just before you need to use it, then close it as soon as you're finished. Since you're using C# you can take advantage of the using block which manages disposable resources for you:

using (var conn = new SqlConnection(connectionString)) {
    try {
        conn.Open();
        // do things here...
    }
    catch (Exception) {
    }
}

Even if you wanted to do something like open the connection asynchronously what purpose would it serve? Your users would have a more responsive UI but still be unable to do anything in the application until the connection was established.


The case which you want to do is not suggestted because you should make the operations with db as possible as quick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜