tags:

views:

92

answers:

3

I thought this was a capture issue but nothing I do works. try to simplify here:

foreach (Question question in Test.Questions)
{
  int id= question.id;
  if(someIDictionary.TryGetValue(id, out value)
  { 
    question.answerobject.number=someinteger;
  }
  else
  {
    question.answerobject.number=someotherinteger;
  }
}

I tried making a temp for question object, but still not working. all results are always last iteration value.

EDIT: Each answerobject is created within each question object as the question is created using linq to sql. then the questions are returned as an IList.

EDIT 2: The issue does not occur if I assign values to another field of question. the issue is only with the answerobject.the values of answerobject are same for all questions (the last assignment).

+2  A: 

What is the problem you are seeing? The "capture" problem only affects async/deferred/threaded code - it shouldn't affect this case.

I wonder if the most likely problem here is that all your Question objects have the same answerobject instance - or even that you have the same Question instance lots of times.


illustration of the "capture propblem" (see comments): this is a problem seen when using a lambda/anon-method; if the iteration variable (question above) is used in the lambda/anon-method, it is "captured" - but in a slightly counter-intuitive way...

For example; we might expect this to print (in an unpredictable order) the numbers 0-9:

int[] vals = {0,1,2,3,4,5,6,7,8,9};
foreach(int i in vals) {
    ThreadPool.QueueUserItem(delegate {
        Console.WriteLine(i);
    });
}
Console.ReadLine();

But it doesn't... we fix it by adding an extra variable:

int[] vals = {0,1,2,3,4,5,6,7,8,9};
foreach(int i in vals) {
    int tmp = i;
    ThreadPool.QueueUserItem(delegate {
        Console.WriteLine(tmp);
    });
}
Console.ReadLine();

This is because the behaviour of captured variables is determined by their lexical scope... the scope of the iteration variable is a bit larger that we would like.

Marc Gravell
What is a "capture" problem ?
nils_gate
I will update...
Marc Gravell
marc see my answer in this thread. does this make more sense?
zsharp
I'm sorry, I still can't decipher from the (little) information available.
Marc Gravell
A: 

what is the scope of value?

Jimmy
A: 

The issue appears to occur when answerobject.number (int?) is assigned "Null" when the object is created. If I try to assign a value during the loop i get the issue above. If howwever I assign an integer when the object is created the problem is gone and i can then addign new values during the loop. Can you explain to me cause I dont get it.

zsharp