1

I have code like this:

type
  TMyDictionary = TDictionary<int, int>;

var
  myDict: TMyDictionary;
  k, v: integer;

  // code to fill the dictionary

  for k in myDict.Keys do
  begin
     v := myDict.Items[k];

     // other stuff
  end;

Randomly I see an exception thrown on 'v := myDict.Items[k];' which says k is invalid.

Anyone else seen this?

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
TheArtTrooper
  • 1,105
  • 8
  • 19

3 Answers3

1

Are you modifying myDict inside the section labeled // other stuff?

Alex B
  • 24,678
  • 14
  • 64
  • 87
1

Looking at CodeCentral I see a number of bugs raised against TDictionary and in particular the enumerator that supports the for ... in ... construct.

TheArtTrooper
  • 1,105
  • 8
  • 19
0

Try to reproduce this problem in one single method with only local variables.

It could be that your using the variable from 2 different threads, or perhaps your updating the elements in the myDict.

I'll try to explain my answer about reproducing it more:

You should create one method which could run on another computer and show the error you're getting.

So for example (Question: I'm getting a divide by zero exception):

var
   i : integer;
begin
   i := 3;
   while (i <= 0) do
   begin
     Writeln(FloatToStr(20/i));
     Dec(i);
   end;
end

If you run this on a computer, people will get the divide by zero exception. So I was able to reproduce the problem. Try to create a snippet as simple as possible to reproduce in a consistent way the problem your having.

Davy Landman
  • 15,109
  • 6
  • 49
  • 73
  • It is as you describe. A single method. Just one thread. All I'm doing inside the loop is looking for the largest 'v' and storing this in a local variable. – TheArtTrooper Mar 12 '09 at 21:39
  • What I meant was, try to make a sample procedure to reproduce it, and post that here so others can look at your sample code. – Davy Landman Mar 13 '09 at 08:14
  • Here's the complete loop: for k in fcm.Keys do begin try v := fcm.Items[k]; if v > max then begin Result := k; max := v; end; except Continue; end; end; – TheArtTrooper Mar 13 '09 at 10:14