×

c# · level 3 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

updates a number in one unbreakable step.

A lock is heavy for one number. adds one as an step: a single action no other thread can split, so no update is lost and no thread waits in a queue. Interlocked.Add(ref total, 250) adds any amount, and both hand back the new value.

The keyword ref hands over the variable itself, not a copy of its value, so the method can change it. It works on fields and local variables, not properties. Read the final number after every task has finished.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

int scans = 0;
long grams = 0;
var belts = Enumerable.Range(1, 4).Select(belt => Task.Run(() =>
{
    for (int parcel = 0; parcel < 5000; parcel++)
    {
        Interlocked.Increment(ref scans);
        Interlocked.Add(ref grams, 250);
    }
}));
await Task.WhenAll(belts);
Console.WriteLine($"Parcels: {scans}, weight: {grams / 1000} kg");

long is a whole-number type for values too big for int, and Interlocked works on both.