473,320 Members | 1,993 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Avoiding "enumeration modified" Exception

19
For my program i need a great deal of completely random, unique, 12 character id's.

So i wrote these three functions

Expand|Select|Wrap|Line Numbers
  1.  
  2. public static string GiveUniqueID(IEnumerator id_key, int count)
  3. {
  4. string id = "";
  5. bool done = false;
  6. while (!done)
  7. {
  8. id = CreateUniqueID(id_key, count);
  9.  
  10. if (id != "@@@")
  11. done = true;
  12. }
  13.  
  14. return id;
  15. }
  16.  
  17. public static string CreateUniqueID(IEnumerator id_key, int count)
  18. {
  19. List<string> ids = new List<string>();
  20. for(int i = 0; i < count; ++i)
  21. {
  22. try
  23. {
  24. id_key.MoveNext();
  25. ids.Add((string)id_key.Current);
  26. }
  27. catch (Exception)
  28. {
  29. return "@@@";
  30. }
  31. }
  32.  
  33. bool done = false;
  34. string id = "";
  35. while (!done)
  36. {
  37. id = UniqueID();
  38.  
  39. if (!ids.Contains(id))
  40. done = true;
  41. }
  42.  
  43. return id;
  44. }
  45.  
  46. public static string UniqueID()
  47. {
  48. string toreturn = Session.IdPrefix;
  49. for (int i = 0; i != 10; ++i)
  50. toreturn += Utility.RandomList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0).ToString();
  51.  
  52. return toreturn;
  53. }
  54.  
So when i need a unique id i simply go string s = GiveUniqueID();, but every while and then the program will freeze because the exception "enumeration modified" keeps repeating in an endless loop.

I am passing the Keys.GetEnumerator(); of dictionaries of varying value types and the count of the dictionary. Since the dictionary's are of varying types i cannot simply pass the dictionary as an argument.

So what i am asking is how to avoid this endless loop?
Dec 31 '08 #1
5 1893
vekipeki
229 Expert 100+
Well, first of all, you should never catch an exception just to ignore it. Remove the try/catch block because you actually want to break the program flow when something goes wrong.

Passing strings with special meanings such as "@@@" is not a very good practice, it will make your code really hard to read, so you should also avoid it.

Are you sure that your exception is "Enumeration modified"? It does not seem that you are actually modifying the enumeration.

My suggestion is to use an IDictionary parameter instead of IEnumerator, it will give you .Count and .Contains(), so you don't have to copy it to a new list every time. Or you can at least use IEnumerable instead of IEnumerator to simplify your code a bit.

Try something like this:

Expand|Select|Wrap|Line Numbers
  1. public static string CreateUniqueID(IDictionary dictionary)
  2. {
  3.     String id = UniqueID();
  4.  
  5.     // Check if our dictionary already contains this key.
  6.     while (dictionary.Contains(id))
  7.         id = UniqueID();
  8.  
  9.     return id;
  10. }
You can also consider using System.Guid class, it generates random GUIDs so you don't have to do it yourself:

Expand|Select|Wrap|Line Numbers
  1. String guid = Guid.NewGuid().ToString();
And please use the CODE tags when posting ! :o)
Dec 31 '08 #2
Plater
7,872 Expert 4TB
I was wondering what happens if you call that function again before the first one is done?
Dec 31 '08 #3
alex21
19
Its a multi thread program, which primarily operates in system memory but uses a database to communicate and synchronize with other instances of the program over the network, so the thread that is synchronizing system data with the database is modifying the dictionary I'm trying to find a unique id for, and to prevent duplicate id's from this i give each client a 2 character id prefix such as "aa".

i managed to fix this problem however simply by making sure it does not endlessly loop, however the problem i have run into now is that the synchronization process is extremely slow, as to read the results of a query the synchronization thread waits on the query thread, this results in only one query being executed while i wait for the result, where as what im aiming for is the execution of many queries without waiting for results.
Jan 1 '09 #4
vekipeki
229 Expert 100+
If your ID doesn't have to be a 10-character string, it would be easiest to simply use:
Expand|Select|Wrap|Line Numbers
  1. String id = Guid.NewGuid().ToString();
This will give you a unique ID every time, without a need for any checks - but it is actually be a hex representation of a 128-bit number.

If you have a really large dictionary, then you will obviously spend some time looking for a unique 10-digit ID (Birthday Paradox is a good sample of collision statistics).

Also, if you are still using try/catch, note that it is one of the largest performance bottlenecks - each caught exception really slows down execution.
Jan 2 '09 #5
Plater
7,872 Expert 4TB
Only the generation of new unique IDs has to be done "one at a time" right? So its ok for your other queries to happen all the time?
Consider only waiting when it deals with the ID generation?
Jan 2 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Codex Twin | last post by:
hello group: The following is a fragment from a schema which defines the EWethnicCategoryStructure type. As you can see, its type is defined by the SimpleType enumeration EWethnicCategoryType....
9
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but...
6
by: timbobd | last post by:
I have a Windows form that displays a database table in a DataGrid. When you click on a row, the row's values get copied to bound TextBoxes below, and when the "Save" button is clicked the database...
3
by: EYIII | last post by:
Is it possible to retrieve the "created by" identity and "modified by" identity for a file (e.g. word doc, .pdf, report, etc) using .NET?
2
by: wsnyder3 | last post by:
I have many forms but all the information is related to one another. I wanted to know if there was a way that if someone updates a account that it will show the last date modified on all the...
4
by: escristian | last post by:
Hello. I'm trying to create an Image so I use something like this: Image newImage = Image.FromFile(filename); Now when it's a bmp file and certain .gif files it gives me an exception that...
8
by: Hermann | last post by:
The standard says "The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields"...
4
by: Daniel | last post by:
Hi guys In regards to the foreach and for loops. I am trying to avoid this exception:exception: "Collection was modified; enumeration operation may not execute....
5
by: arnuld | last post by:
this is a programme that counts the "lengths" of each word and then prints that many of stars(*) on the output . it is a modified form of K&R2 exercise 1-13. the programme runs without any...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.