there is a code snippet

int readen = 1; int i = 0; while (readen > 0) { if (msList.Count >= 20) { Thread.Sleep(200); continue; } else { msList.Add(new MemoryStream()); gzsList.Add(i, new GZipStream(msList.Last(), CompressionMode.Compress)); readen = fsIn.Read(buffer, 0, buffer.Length); compressTasks.Add(new Task(() => { (gzsList[i] as GZipStream).Write(buffer, 0, readen); })); i++; compressTasks.Last().Start(); } } 

the problem is that in the line compressTasks.Add(new Task(() => { (gzsList[i] as GZipStream).Write(buffer, 0, readen); })); incomprehensible things happen: if the condition is met, the thread does not fall asleep, and execution goes to this line and, accordingly, an exception is thrown out, moreover, depending on the type of the gzslist collection (for List``System.InvalidOperationException KeyNotFoundException NullReferenceException . List``System.InvalidOperationException , Dictionary KeyNotFoundException , Hashtable NullReferenceException . If you remove the condition, then all exceptions are equal, but with a different size of the collection (depends on the launch (from 20 to 50)

  • And why do you use Task as streams? Why not modern async / await? - VladD
  • And yet, it is not clear why the addition of Task 'to the collection should lead to a sleep stream. - VladD
  • You also shared the variable i between Task 's, this is a time bomb (think why). - VladD
  • It seems to me, or is the buffer there too common? - zRrr
  • Not adding should lead to the flow falling asleep, and after adding too many elements in the collection (tobish consumer slower producer), you need to wait for free space in the collection. And it is possible in more detail why it is bad to fumble int between tasks? It is passed by value and in theory there should be no problems - Artemiy Borodin

0