使用多线程建立与数据库的多重连接 [英] establishing a multible connections to the database using multithreading

查看:63
本文介绍了使用多线程建立与数据库的多重连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





任何人都可以帮忙解决以下问题。



问题出在何时我在Windows应用程序中实现多线程,而第一个线程正在处理(function1),第二个线程也试图调用相同的function1,那时我得到以下异常:



System.InvalidOperationException:已经有一个与此命令关联的打开DataReader必须先关闭。



我尝试使用Lock语句数据从数据库中读取并存储在数据集中的位置。但它不起作用。



任何人都可以帮我解决这个问题。



先谢谢你..



Naresh Reddy

Hi ,

Can anyone help to resolve the below problem.

The problem is when i'm implementing a multithreading in windows application while the first thread is being processing(function1) and second thread also trying to call the same function1 by that time i'm getting the below exception:

System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.

I tried using the "Lock" statement where the data is reading from the database and storing in dataset.But it's not working.

Can anyone please help me to resolve this issue.

Thank you in Advance..

Naresh Reddy

推荐答案

SqlConnection一次只能支持一个SqlDataReader,所以当你的代码试图在另一个线程中创建第二个时,它会抱怨。

解决方案是只使用本地SqlConnection和SqlCommand对象:

An SqlConnection can only support one SqlDataReader at a time, so when your code tries to create a second one in a different thread, it complains.
The solution is to only ever use "local" SqlConnection and SqlCommand objects:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT Id, description FROM myTable", con))
        {
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["Id"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", id, desc);
                }
            }
        }
    }

这也确保连接尽快关闭和处理,以免浪费SQL Server上的资源。

That also ensures that connections are closed and disposed as soon as possible, so as not to waste resources at SQL Server.


这篇关于使用多线程建立与数据库的多重连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆