Hi,
Please consider the following code snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
namespace ConsoleApplication4
{
class Program
{
public DataTable DT { get; private set; }
public const string PrimaeyKeyColumnName = @"PK";
public const string ValueColumnName = @"Value";
static void InitDT()
{
DT.Columns.Add(PrimaeyKeyColumnName, typeof(string));
DT.Columns.Add(ValueColumnName, typeof(string));
DT.PrimaryKey = new DataColumn[] { DT.Columns[PrimaeyKeyColumnName] };
}
void UpdateDT(string primaryKey, string value)
{
DataRow dr = null;
lock (DT.Rows.SyncRoot)
{
if (DT.Rows.Contains(primaryKey))
{
dr = DT.Rows.Find(primaryKey);
dr[ValueColumnName] = value;
}
else
{
DT.Rows.Add(primaryKey, value);
}
}
if (dr == null)
{
dr = DT.Rows.Find(primaryKey);
}
ProcessDR(dr);
}
void ProcessDR(DataRow dataRow)
{
}
static void Main(string[] args)
{
InitDT();
}
}
}
Look at the ProcessDR method. I'm hitting that error infrequently / in a random manner (I know that's not the most scientific use of the word 'random').
I think, as a copy of the reference to the DataRow is passed to the ProcessDR method, and while ProcessDR accesses its column cells, sometimes the CLR throws that error because of the DataTable DT being in some "intermittent" state (remember the DataTable is being updated very frequently from a separate context).
Now 2 questions:
1. Is my understanding of the cause of the error correct?
2. Should I clone the DataRow before passing it to ProcessDR? If yes, what's the most performance-effective way to do that?
Regards