Chapter 15. Threading

A thread represents a single flow of execution logic in a program. Some programs never need more than a single thread to execute efficiently, but many do. Threading in .NET allows you to build responsive and efficient applications. Many applications need to perform multiple actions at the same time (like supporting simultaneous user interface interaction and data processing)—threading allows the developer to provide this capability. Once you have multiple threads of execution in your application, you need to start thinking about what data in your application needs to be protected from multiple access, what data could cause threads to develop an interdependency that could lead to deadlocking (where Thread A has a resource that Thread B is waiting for and Thread B has a resource that Thread A is waiting for), and how to store data relative to the individual threads. We will explore some of these issues to help you take advantage of this wonderful capability of the .NET Framework, while explaining the areas to beware and items to keep in mind while designing and creating your multithreaded application.

15.1. Creating Per-Thread Static Fields

Problem

Static fields, by default, are shared between threads within an application domain. You need to allow each thread to have its own nonshared copy of a static field, so that this static field can be updated on a per-thread basis.

Solution

Use ThreadStaticAttribute to mark any static fields as not being shareable between ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.