Created
November 21, 2017 12:50
-
-
Save 0liver/f3ff2b36b029845c01656a8919f430e7 to your computer and use it in GitHub Desktop.
Test code to show non-thread-safety of List<>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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