I have tried the code below and it throws exceptions saying that the query requires an open connection, and that the current state is open/opening/closed.
It is a Parallel.ForEach loop creating threads, and I want them to open the connection to the SQL Server database and insert something there. I followed the patterns to handle parallelism in other questions here, but they don't work for me.
Can someone throw some light on this this? How to make this happen?
Connection open error?

Connection closed error

private static void CreateResultTable()
{
Parallel.ForEach(_fakeTableFileFull, tableRow =>
{
var fileRow = Regex.Split(tableRow, PatternExFile);
SearchForConfirm(fileRow[3], fileRow[1], fileRow[2]);
});
}
private static void SearchForConfirm(string id, string number, string date)
{
if (tokenChecksum.ContainsKey(id))
{
WriteLineToResultFile(number, date, tokenChecksum[id], id);
}
}
private static void WriteLineToResultFile(string number, string date, string confirm, string id)
{
using (Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"]
.ConnectionString))
{
Conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PanChecksums] " +
"([number], " +
"[Id]) " +
"VALUES " +
"(" + Int64.Parse(id) +
"," + "'" + confirm + "'" + ")", Conn);
cmd.ExecuteNonQuery();
}
using (Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"]
.ConnectionString))
{
Conn.Open();
SqlCommand cmd = new SqlCommand("SET IDENTITY_INSERT IdNumber ON;", Conn);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("INSERT INTO [dbo].[IdNumber] " +
"([Id], " +
"[number], " +
"[Month], " +
"[Year]) " +
"VALUES " +
"(" + "'" + id + "'" + "," +
Int64.Parse(number) + "," +
"'" + date.Substring(0, 2) + "'" + "," +
"'" + date.Substring(2, 2) + "'" + ")", Conn);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("SET IDENTITY_INSERT IdNumber ON;", Conn);
cmd.ExecuteNonQuery();
}
Connis a field in this class and so all of your parallel threads are over-writing the variable with what should be something only held locally.