what is the best way to make a DataTable thread safe? DataTable.AcceptChanges() will throw exception

R

Ryan Liu

Hi,

In the .NET Framework SDK documentation, I can see DataRow.AcceptChanges
method will throw RowNotInTableException exeception.

And in DataTable.AcceptChanges(), the documentation does not mention it will
throw any exception, but in my code (multi-thread), I see it throw
exceptions at two situations:

dr = this.currentQuotaUserDt.NewRow();

this.currentQuotaUserDt.Rows.Add(dr);

this.currentQuotaUserDt.AcceptChanges();

Last line throw exception : Cannot perform this operation on a row not in
the table.

(Code is more complex than what list here and it is multi-thread
enviorment.)

==============
this.currentDr.Delete();
this.currentDr.Table.AcceptChanges();

The last line will throw:
System.Data.RowNotInTableException: Cannot perform this operation on a row
not in the table.
at System.Data.DataTable.SetOldRecord(DataRow row, Int32 proposedRecord)
at System.Data.DataTable.CommitRow(DataRow row)
at System.Data.DataTable.AcceptChanges()



Thanks,
Ryan
 
G

Guest

Ryan,
It is not clearly evident from your post how you could have gotten the
exception you report, but if you want to ensure thread safety, you can use
the lock statement on a local object variable:

object locker = new object();
lock (locker)
{

// your code here


}

--Peter
 
N

Nicholas Paldino [.NET/C# MVP]

Peter,

That's assuming that the data table is only being accessed in that
method, and that method is the only one that is being called from other
threads.
 
G

Guest

Nick,
Absolutely; in the interest of completeness, the OP would have to "protect"
any method that accesses the datatable and which could possibly be called by
multiple threads.
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com




Nicholas Paldino said:
Peter,

That's assuming that the data table is only being accessed in that
method, and that method is the only one that is being called from other
threads.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Peter Bromberg said:
Ryan,
It is not clearly evident from your post how you could have gotten the
exception you report, but if you want to ensure thread safety, you can use
the lock statement on a local object variable:

object locker = new object();
lock (locker)
{

// your code here


}

--Peter
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top