超时异常导致SqlDataReader关闭?

时间:2009-11-12 01:33:03

标签: c# sql sqldatareader

我正在尝试从数据库中提取一些二进制数据并将其写入pdf文件。在大多数情况下,这是在游泳,但偶尔的一行数据似乎抛出一个特定的错误 -

超时已过期。操作完成之前经过的超时时间或服务器没有响应。

请记住,这只发生在少数行上,并且从不随机。相同的行总是抛出异常。我不确定为什么会抛出异常,但我可以跳过导致问题并继续前进的行。然而,我的问题是,当我捕获异常然后尝试移动到下一行时,我遇到另一个异常 -

InvalidOperationException - 读取器关闭时无效尝试调用Read。

这是否意味着读者一旦遇到异常就会自动关闭?如何在没有任何戏剧的情况下继续前进到下一行?

        while (sdrReader.Read()) // Second exception happens here
        {
            try
            {
                byte[] byteData = new Byte[(sdrReader.GetBytes(0, 0, null, 0, int.MaxValue))]; // first exception happens here
                sdrReader.GetBytes(0, 0, byteData, 0, byteData.Length);
                string strOutputFileName = sdrReader.GetInt32(1).ToString() + ".pdf";
                msMemoryStreams = new MemoryStream();
                msMemoryStreams.Write(byteData, 0, byteData.Length);
                byte[] byteArray = msMemoryStreams.ToArray();

                msMemoryStreams.Flush();
                msMemoryStreams.Close();

                writeByteArrayToFile(byteData, txtFilesPath.Text + "\\" + strOutputFileName);
            }
            catch (Exception e)
            {
                Logger.Write("Document failed to convert: " + e.Message);
            }
        }

根据要求进行堆栈跟踪 -

   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
   at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParserStateObject.ReadNetworkPacket()
   at System.Data.SqlClient.TdsParserStateObject.ReadBuffer()
   at System.Data.SqlClient.TdsParserStateObject.ReadByteArray(Byte[] buff, Int32 offset, Int32 len)
   at System.Data.SqlClient.TdsParser.ReadSqlValue(SqlBuffer value, SqlMetaDataPriv md, Int32 length, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlDataReader.ReadColumnData()
   at System.Data.SqlClient.SqlDataReader.ReadColumn(Int32 i, Boolean setTimeout)
   at System.Data.SqlClient.SqlDataReader.GetSqlBinary(Int32 i)
   at System.Data.SqlClient.SqlDataReader.GetBytesInternal(Int32 i, Int64 dataIndex, Byte[] buffer, Int32 bufferIndex, Int32 length)
   at System.Data.SqlClient.SqlDataReader.GetBytes(Int32 i, Int64 dataIndex, Byte[] buffer, Int32 bufferIndex, Int32 length)
   at Pdf2Rtf.Form1.Read() in F:\Code\Pdf2Rtf\Pdf2Rtf\Pdf2Rtf\Form1.cs:line 77
   at Pdf2Rtf.Form1.btnRead_Click(Object sender, EventArgs e) in F:\Code\Pdf2Rtf\Pdf2Rtf\Pdf2Rtf\Form1.cs:line 24
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at Pdf2Rtf.Program.Main() in F:\Code\Pdf2Rtf\Pdf2Rtf\Pdf2Rtf\Program.cs:line 18
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

2 个答案:

答案 0 :(得分:13)

看起来你的SqlCommand超时 - 当你拨打ExecuteReader时,相关的命令仍然保持打开状态,并且在你读完之前很容易超时。正如SqlCommand.CommandTimeout文档中所述:

  

此属性是累积的   超时期间所有网络读取超时   命令执行或处理   结果。超时仍然可能发生   返回第一行后,和   不包括用户处理时间,   只有网络阅读时间。

当命令超时时,它会关闭读取器,您无法从中恢复。

尝试解决此问题的第一件事是大幅增加CommandTimeout,以确保您可以继续。

接下来,如果您尚未执行此操作,则可能有助于使用ExecuteReader重载,您可以指定CommandBehavior,并传递CommandBehavior.SequentialAccess(根据MSDN主题"Retrieving Large Data (ADO.NET)“)。

最后,您还可以尝试将读取分成大块记录。

答案 1 :(得分:1)

如果SQL Error Severity小于17,则可以将SqlConnection.FireInfoMessageEventOnUserErrors = true设置为处理异常作为警告。无论如何,任何大于严重级17的内容都会close the connection