Will it crash my process

2012/12/10

Will it crash my process

here is a short question,
it was taken from a real life bug that occurs at one of my customers.

will the following code crash the process?

Code Snippet
  1. List<object> items = new List<object>();
  2.  
  3. try
  4. {
  5.     Parallel.For(0, 10000000, t =>
  6.     {
  7.         items.Add("1");
  8.     });
  9.  
  10. }
  11. catch (AggregateException ex)
  12. {
  13. }

it is a non thread safe code that should throw an IndexOutOfRangeException.

but it wouldn’t crash the process,
but what about the following code?

Code Snippet
  1. List<object> items = new List<object>();
  2.  
  3. try
  4. {
  5.     Parallel.For(0, 10000000, t =>
  6.     {
  7.         items.Add("1");
  8.     });
  9.  
  10. }
  11. catch (AggregateException ex)
  12. {
  13. }
  14.  
  15. items.Add("?");

Exception, .NET. Parallel. Thread, safe

despite the fact that the last addition is seem totally safe,
it will occasion crash the process.

so why does it happens?

the parallel code part was putting the list itself in a corrupted state,
which mean that further access will result in an exception.

the problem is that further access may be locate in a different code file, ant this will make this bug a very illusive one.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*