C# Threading: Hans-Wolfgang Loidl
C# Threading: Hans-Wolfgang Loidl
Hans-Wolfgang Loidl
<[email protected]>
School of Mathematical and Computer Sciences,
Heriot-Watt University, Edinburgh
Semester 1 — 2018/19
0
Based on: "An Introduction to programming with C# Threads"
By Andrew Birrell, Microsoft, 2005 hwu-logo.png
Examples from "Programming C# 5.0", Jesse Liberty, O’Reilly. Chapter 20.
H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC — 2018/19 C# Threading 1 / 33
Processes and Threads
hwu-logo.png
hwu-logo.png
hwu-logo.png
hwu-logo.png
hwu-logo.png
Thread Creation.
Mutual Exclusion.
Event waiting.
Waking up a thread.
The above primitives are supported by C#’s
System.Threading namespace and C# lock statement.
hwu-logo.png
hwu-logo.png
hwu-logo.png
hwu-logo.png
0
Examples from “Programming C# 3.0”, Jesse Liberty, O’Reilly. Chapter 20.
H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC — 2018/19 C# Threading 12 / 33
Example: Swap (cont’d)
hwu-logo.png
hwu-logo.png
hwu-logo.png
hwu-logo.png
hwu-logo.png
Example:
Thread A opens a file
Thread B writes to the file
I =⇒ The program is successful, if A is fast enough to open
the file, before B starts writing.
hwu-logo.png
hwu-logo.png
hwu-logo.png
Example:
Thread A acquires resource 1
Thread B acquires resource 2
Thread A wants 2, so it calls Wait to wait for 2
Thread B wants 1, so it calls Wait to wait for 1
=⇒ Again, partial order can be used to avoid the
deadlock.
hwu-logo.png
hwu-logo.png
hwu-logo.png
0
See Asynchronous Programming with Async and Await (C# and Visualhwu-logo.png
Basic)
H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC — 2018/19 C# Threading 31 / 33
Resources
Sample sources and background reading:
threads2.cs: incrementer/decrementer
threads4.cs: incrementer/decrementer with marks
mulT.cs: expanded multi-threading example
BgWorker.cs: background worker example
asyncFiles.cs: async example
See this screencast on LinkedIn Learning on “Async
Programming in C#”
See this section in “Threading in C#”, by Joe Albahari
See this MSDN article on “Threading and Asynchronous
Programming”
See Asynchronous Programming with Async and Await
(C# and Visual Basic) hwu-logo.png