Skip to content

Instantly share code, notes, and snippets.

@0liver
Created November 21, 2017 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0liver/f3ff2b36b029845c01656a8919f430e7 to your computer and use it in GitHub Desktop.
Save 0liver/f3ff2b36b029845c01656a8919f430e7 to your computer and use it in GitHub Desktop.
Test code to show non-thread-safety of List<>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Tests {
[TestFixture]
public class ConcurrentListAddTest {
[Test]
public void Should_eventually_throw_exception() {
var r = new Random();
var list = new List<object>();
try {
while (true) {
var tasks = Enumerable
.Range(1, 5)
.Select(i => Task.Run(async () => {
list.Add(new object());
await Task.Delay(r.Next(75, 125));
list.Add(new object());
await Task.Delay(r.Next(75, 125));
list.Add(new object());
list.Add(new object());
await Task.Delay(r.Next(75, 125));
list.Add(new object());
list.Add(new object());
list.Add(new object());
await Task.Delay(r.Next(75, 125));
list.Add(new object());
})).ToArray();
Task.WaitAll(tasks);
if (list.Any(o => o == null))
throw new NullReferenceException();
}
}
catch (AggregateException ex) {
var exes = string.Join(", ", ex.InnerExceptions.Select(e => e.GetType().Name).Distinct());
Console.WriteLine("Caught {0}", exes);
}
catch (NullReferenceException) {
Console.WriteLine("Caught NullReferenceException");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment