2013-07-05 137 views
2

我有個問題:如何在asp.net MVC頁面中處理操作超時。加載正在查詢數據庫SQL Server的頁面時,會加載產品。有時它說等待操作超時。如何處理它。等待操作超時mvc

+0

回顧你的代碼。檢查你的SQL查詢,這得花多少CPU服用和資源.. –

回答

4

爲了避免在運行非常長的查詢時發生等待操作超時異常,請更改SQL命令屬性並允許該命令在調用超時之前等待較長時間。

using System; 
using System.Data.SqlClient; 
/// 
public class A { 
    /// 
    public static void Main() { 
    string connectionString = ""; 
    // Wait for 5 second delay in the command 
    string queryString = "waitfor delay '00:00:05'"; 
    using (SqlConnection connection = new SqlConnection(connectionString)) { 
     connection.Open(); 
     SqlCommand command = new SqlCommand(queryString, connection); 
     // Setting command timeout to 1 second 
     command.CommandTimeout = 1; 
      try { 
       command.ExecuteNonQuery(); 
       } 
      catch (SqlException e) { 
       Console.WriteLine("Got expected SqlException due to command timeout "); 
       Console.WriteLine(e); 
     } 
    } 
} 

}

的LINQ的執行到SQL查詢可能需要更長的時間&超過DataContext類的CommandTimeout屬性的默認值。 默認值是30秒。 我們可以在每次創建LINQ to SQL DataContext對象並調用查詢之前設置CommandTimeout的值。

#region Constructors 

    /// <summary> 
    /// Initializes a new FrameworkEntities object using the connection string found in the 'FrameworkEntities' section of the application configuration file. 
    /// </summary> 
    public FrameworkEntities() : base("name=FrameworkEntities", "FrameworkEntities") 
    { 
     this.ContextOptions.LazyLoadingEnabled = true; 
     this.CommandTimeout = 300; 
     OnContextCreated(); 
    } 

    /// <summary> 
    /// Initialize a new FrameworkEntities object. 
    /// </summary> 
    public FrameworkEntities(string connectionString) : base(connectionString, "FrameworkEntities") 
    { 
     this.ContextOptions.LazyLoadingEnabled = true; 
     this.CommandTimeout = 300; 
     OnContextCreated(); 
    } 

    /// <summary> 
    /// Initialize a new FrameworkEntities object. 
    /// </summary> 
    public FrameworkEntities(EntityConnection connection) : base(connection, "FrameworkEntities") 
    { 
     this.ContextOptions.LazyLoadingEnabled = true; 
     this.CommandTimeout = 300; 
     OnContextCreated(); 
    } 

    #endregion 
+0

'command.CommandTimeout = 0;'將會是無限的? –

+0

零是無限超時。 當來自SQL SERVER實例的響應被分解爲多個網絡數據包時,連接將錯誤地結合,並且會發生一般網絡錯誤。 – AnandMohanAwasthi

+0

我無法在任何地方找到此類文檔。謝謝。 –