2015-06-01 59 views
0

我正在使用Parallel.For并发调用如下。parallel.for循环给出超时异常

SqlConnection connection = new SqlConnection(connectionString);       
connection.Open(); 
SqlCommand cmd = new SqlCommand(); 
//SqlDataReader reader;        
cmd.CommandType = CommandType.Text; 
cmd.Connection = connection; 
Parallel.For(0, 100, delegate(int i) 
{ 
    //insert into database; 
    cmd.CommandText = string.Format("insert into Service_LoadTest(id,ServiceCallcount) values ({0},'Call_{1}')", i, i);        
    cmd.ExecuteNonQuery(); 
    }); 

插入一些数高达70后,我收到超时异常为“超时过期。超时时间已过之前,操作完成或服务器没有响应。”我已经设置了引黄串超时财产,但没有运气。请帮忙。

+3

SqlCommand不是线程安全的,你不能这样做。 –

+1

你是否希望使用'Parallel.For'来加速你的数据库插入? – Enigmativity

+1

另一端是单写头。除非你在另一端有一些奇特的切断点,否则这将不会更快。打开每个插入连接的解决方案不会更快。 – Paparazzi

回答

2

您的代码不是线程安全的。尝试所有的代码移动到循环:

Parallel.For(0, 100, delegate(int i) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    {       
     connection.Open(); 

     SqlCommand cmd = new SqlCommand(); 

     cmd.CommandType = CommandType.Text; 
     cmd.Connection = connection; 

     cmd.CommandText = string.Format("insert into Service_LoadTest(id,ServiceCallcount) values ({0},'Call_{1}')", i, i);        
     cmd.ExecuteNonQuery(); 
    } 
}); 
+0

Thanks.It工作。 – user1595214

+0

你正在打开连接而没有关闭它们,你将遇到问题。 SqlConnection对象需要放入'using'块中,以便它们正确处理和关闭。 –

+0

@ScottChamberlain谢谢你指出。更新了答案。 – RagtimeWilly

0

而不是创造的SqlConnection每一次的SqlCommand对象,并与intialising那些单独调用的ExecuteNonQuery对于每个查询,你应该串联所有查询和该级联查询调用的ExecuteNonQuery只有一次的。

对于上面的实现,只需追加CommandText中的所有查询,由';'分隔然后调用ExecuteNonQuery。