O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required