Wednesday, 15 August 2012

c# - Using the Concurrent Dictionary - Thread Safe Collection Modification -



c# - Using the Concurrent Dictionary - Thread Safe Collection Modification -

recently running next exception when using generic dictionary

an invalidoperationexception has occurred. collection modified

i realized error because of thread safety issues on static dictionary using.

a little background: have application has 3 different methods related issue.

method iterates through dictionary using foreach , returns value. method b adds info dictionary. method c changes value of key in dictionary.

sometimes while iterating through dictionary, info beingness added, cause of issue. maintain getting exception in foreach part of code iterate on contents of dictionary. in order resolve issue, replaced generic dictionary concurrentdictionary , here details of did.

aim : main objective remove exception

for method b (which adds new key dictionary) replaced .add tryadd

for method c (which updates value of dictionary) did not create changes. rough sketch of code follows :

static public int changecontent(int para) { foreach (keyvaluepair<string, custobject> pair in static_container) { if (pair.value.propa != para ) //pending cancel { pair.value.data_id = prim_id; //i updating content homecoming 0; } } homecoming -2; }

for method a - iterating on dictionary , running code stops (in debug mode) , visual studio informs me error occured.the code using similar following

static public custobject retrieveorderdetails(int para) { foreach (keyvaluepair<string, custobject> pair in static_container) { if (pair.value.cust_id.equals(symbol)) { if (pair.value.orderstatus != para) { homecoming pair.value; //found } } } homecoming null; //not found }

are these changes going resolve exception getting.

edit:

it states on this page method getenumerator allows traverse through elements in parallel writes (although may outdated). isnt same using foreach ?

before doing foreach() seek out copying container new instance

var unboundcontainer = static_container.tolist(); foreach (keyvaluepair<string, custobject> pair in unboundcontainer)

also think updating value property not right thread safety perspectives, refactor code utilize tryupdate() instead.

c# concurrency

No comments:

Post a Comment