2013-10-01 89 views
0

我是ASP.NET新手。我想我不知道何時使用USING語句。當我在我的代碼中嘗試它時,例如下面。它有時需要永久​​和超時。當我不使用時運行,它工作正常。使用聲明需要很長時間,有時會超時

有人可以澄清USING聲明嗎?我什麼時候應該使用它,什麼時候不應該使用它。

此代碼是永久存在並超時。 ...有些代碼在這裏。打開數據庫連接執行....

cmdinsert.CommandText = insertcommand; 
cmdinsert.ExecuteNonQuery(); 

Using (SqlCommand command = new SqlCommand("Import_EvaluationMatch", connSQL, trans)) 
    { 
    command.CommandType = CommandType.StoredProcedure; 
    command.Parameters.Add("@RefNum", SqlDbType.Int).Value = RefNum; 
    command.ExecuteNonQuery(); 
    } 
trans.Commit(); 
connSQL.Close(); 

Response.Write("Import Successfully"); 
Response.Redirect("Default.aspx"); 
Response.End(); 

刪除了USING語句,它工作正常。

... Some codes up here. Open DB Connection Execute.... 
cmdinsert.CommandText = insertcommand; 
cmdinsert.ExecuteNonQuery(); 


// --- Now calling the stored procedure to process all this imported items. 
SqlCommand command = new SqlCommand("Import_EvaluationMatch", connSQL, trans); 
    command.CommandType = CommandType.StoredProcedure; 
    command.Parameters.Add("@RefNum", SqlDbType.Int).Value = RefNum; 
    command.ExecuteNonQuery(); 
trans.Commit(); 
connSQL.Close(); 

回答

1

using聲明不需要任何時間。需要花費的時間是清理你的SqlCommand。當您使用using聲明時,清理將在內部進行。當你不使用它時,每當垃圾收集器決定時,清理就會隨機發生。

這是「現在支付我,還是以後支付我」的情況。

問題在於您的Import_EvaluationMatch存儲過程耗時過長。

+0

感謝您的回覆。嗯,我運行Import_EvaluationMatch,它非常快。所以清理真的需要那麼長時間? – milacay

+0

顯然,是的。也許這與你使用交易有關。儘量不要使用交易,看看它的速度有多快(只是作爲一種二次探測技術)。 –