I've been experimenting lately with async-await and I still cannot get some things to work.
Why does this code not always result with '100' being written to console?
static List<int> list = new List<int>();
static void Main(string args)
private async static void NewMethod()
var tasks = new List<Task>();
for (int i = 0; i < 100; i++)
static async Task Func(int i)
The reason you experience the inconsistency in the number of elements is because
List<T> isn't thread-safe.
await Task.Delay(100), the continuation, which adds elements to the list happens on an arbitrary thread pool, concurrently, because multiple tasks are executing. If you switch you implementation to use
ConcurrentBag<int>, this wont happen.