c# · level 3 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Hand out tickets. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Threading;
int tickets = 0;
int first = Interlocked.Increment(ref tickets);
int second = Interlocked.Add(ref tickets, 10);
Console.WriteLine($"{first} {second} {tickets}");
your turn
Your turn. Count the likes.
On line 11, choose the Interlocked method that adds one to likes in a single safe step.
output
press run to see what happens
fix it
The fuel pumps will not compile. Can you fix it?
output
press run to see what happens
- C# says argument 1 must be passed with a keyword, on line 11.
- Without it,
Addwould get a copy oflitresand could not change the real one. - Write
Interlocked.Add(ref litres, 3);on line 11, then run.
nailed it
your counters are safe without locks. :D
- An atomic step cannot be split by another thread.
Interlocked.IncrementandAddreturn the new value.refhands over the variable itself.
new words in your collection
- atomic
- Interlocked
- ref
This lesson isn’t saved. A free account remembers every lesson you finish.