Skip to content

Threading

Frans Lytzen edited this page Oct 30, 2020 · 1 revision

Unlike in Javascript, async code in C# does include threads. In short, any code after a call to await may run on a different thread and it is entirely possible that when you are running multiple async calls in parallel that some of the "callbacks" will happen simultaneously on different threads. For all the details, look at this video.

Example

If you run this code, you will see the problem. This has nothing to do with this library and everything to do with the nature of async in C#. However, in a lot of every day async code you are not running things in parallel, so you may not have run into this before. To avoid this, you need to make sure you make any code after the await statement is threadsafe. In this simple example, you could use Interlocked.Increment instead of ++.

ThreadPool.SetMinThreads(100,100); 
var enumerable = Enumerable.Range(1, 10000);
int written = 0;

await enumerable.SafeParallelAsync(async number => 
    {
        await Task.Delay(1);
        written++;
        if (number % 1000 == 0)
        {
            Console.WriteLine($"Input: {number}. Written: {written}");
        }
        
    });

Console.WriteLine(written);
Clone this wiki locally