0

I have some work I want to run in seperate tasks, for demonstration purposes I simplied the code into just filling a list with the numbers 1 - 1000. This is what I try:

public struct ExampleStruct
        {
            public String number;
            public String otherData;
        }
List<String> results = new List<string>();
List<Task> TList = new List<Task>();

void mainFunc()
        {
            for(int i = 0; i < 1000; i++)
            {
                ExampleStruct.no = i.ToString();
                ExampleStruct.zip = "3333";
                TList.Add(Task.Run(() => GetDataFor(ExampleStruct)).ContinueWith(ct => incrementProgress(worker)));
            }
            Task.WaitAll(TList.ToArray());
        }

private void GetDataFor(ExampleStruct dataInput)
        {
            results.Add(dataInput.number.ToString());
        } 

Now I get the following output in my list:

4
4
5
5
5
14
17
19
39
76
80
123
159
168
201
233
239
256
263
269
275
280
295
300
315
322
327
334
337
340
345
347
357
367
378
382
384
387
389
396
400
401
403
409
416
417
418
418
429
433
436
437
439
441
444
454
466
468
470
471
531
547
547
548
550
555
561
563
568
569
570
570
570
570
570
570
573
575
576
584
589
591
593
595
595
595
623
676
694
694
697
706
711
748
754
754
759
776
783
783
791
802
813
844
882
890
908
929
943
958
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999
999

Why does this happen? Why are so many numbers skipped and the list ends up being filled with the last entry (999). I would expect an output just counting 1-1000, perhaps not in the right order if different threads dont start in order from 1-1000. Yet I expect every number to only occur once in the list.

Gustav
  • 11
  • 4
  • 1
    I expect that the *variable* that contains an `ExampleStruct` (that appears to also be named `ExampleStruct`) is declared outside of the loop, but it's hard to tell since you *haven't included that variable in your example* – Damien_The_Unbeliever Jan 20 '23 at 14:24
  • It looks like a problem with your scope of `ExampleStruct` – smoksnes Jan 20 '23 at 14:24

0 Answers0