使用ADO.Net的查询的连接超时异常

dra*_*gon 9 .net c# ado.net timeout

更新:看起来查询不会抛出任何超时.连接超时.

这是用于执行查询的示例代码.有时,在执行耗时的查询时,会抛出超时异常.

不能使用以下任何技术:1)增加超时.2)使用回调异步运行它.这需要以同步方式运行.

请建议任何其他技术,以便在执行耗时的查询时保持连接活动?

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}
Run Code Online (Sandbox Code Playgroud)

Gul*_*zim 16

由于您使用的ExecuteNonQuery不返回任何行,因此您可以尝试这种基于轮询的方法.它以asyc方式执行查询(没有回调),但应用程序将等待(在while循环内),直到查询完成.来自MSDN.这应该解决超时问题.请试一试.

但是,我同意其他人的意见,你应该多考虑优化查询,以便在30秒内执行.

        IAsyncResult result = command.BeginExecuteNonQuery();

        int count = 0;
        while (!result.IsCompleted)
        {
            Console.WriteLine("Waiting ({0})", count++);
            System.Threading.Thread.Sleep(1000);
        }
        Console.WriteLine("Command complete. Affected {0} rows.",
        command.EndExecuteNonQuery(result));
Run Code Online (Sandbox Code Playgroud)

  • 我不是百分百肯定,但我不认为SqlConnection可以超时 - 据我所知,只打开一个新连接可能会超时(默认为15秒).所以我仍然认为命令超时(如果命令在尝试从连接读取时超时,则可能看起来像连接超时.). (2认同)