TDictionary - invalid key

820 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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

1
On

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

3
On

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.