2015-06-01 63 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。