none
DataTable to csv file with ContextSwitchDeadlock error RRS feed

  • Question

  • I am trying to save the records from a DataTable into a csv file. I am using the following code which activates an MDA stating "ContextSwitchDeadlock was detected". What can I do to correct this?

     

    Dim ResultConn As New SqlConnection(DestConnStr)

    Dim ResultCmd As New SqlCommand

    ResultCmd.CommandType = CommandType.Text

    ResultCmd.CommandText = "SELECT * FROM MyTable"

    ResultCmd.Connection = ResultConn

     

    Dim ResultAdapter As New SqlDataAdapter

    ResultAdapter = New SqlDataAdapter(ResultCmd)

     

    Dim ResultTable As New DataTable("Result")

    ResultAdapter.Fill(ResultTable)

     

    'start write to csv file

    Dim sExport As New Text.StringBuilder

      For Each dr As DataRow In ResultTable.Rows

        For Each field As Object In dr.ItemArray

          sExport.Append(field.ToString & ",")

        Next field

        sExport.Replace(",", vbNewLine, sExport.Length - 1, 1)

      Next dr

    My.Computer.FileSystem.WriteAllText(FilePath, sExport.ToString, False)

    'end write to csv file

    Sunday, September 16, 2007 7:19 PM

Answers

  • I changed the write to csv file code to the following and everything works fine now.

     

    'start write to csv file

    Dim ResultWriter As System.IO.StreamWriter

    ResultWriter = New System.IO.StreamWriter(FilePath)

    'first write line with field names

    Dim sDelimiter As String = ""

    Dim StrBuilder As New System.Text.StringBuilder

    For Each col As DataColumn In ResultTable.Columns

    StrBuilder.Append(sDelimiter).Append(col.ColumnName)

    sDelimiter = ","

    Next col

    ResultWriter.WriteLine(StrBuilder.ToString())

    ' then write all the rows

    sDelimiter = ""

    For Each row As DataRow In ResultTable.Rows

    StrBuilder = New System.Text.StringBuilder

    For Each col As DataColumn In ResultTable.Columns

    StrBuilder.Append(sDelimiter).Append(row(col.ColumnName))

    sDelimiter = ","

    Next col

    sDelimiter = ""

    ResultWriter.WriteLine(StrBuilder.ToString())

    Next row

    If Not ResultWriter Is Nothing Then ResultWriter.Close()

    'end write to csv file

    Sunday, September 16, 2007 8:19 PM