O'Reilly logo

Professional C# 4 and .NET 4 by Morgan Skinner, Karli Watson, Jay Glynn, Bill Evjen, Christian Nagel

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 20. Threads, Tasks, and Synchronization

WHAT'S IN THIS CHAPTER?

  • An overview of threading

  • Lightweight threading using delegates

  • Thread class and thread pools

  • Tasks

  • Parallel class

  • Cancellation framework

  • Threading issues

  • Synchronization techniques

  • Timers

  • Event-based asynchronous pattern

There are several reasons for using threading. Suppose that you are making a network call from an application that might take some time. You don't want to stall the user interface and just let the user wait until the response is returned from the server. The user could perform some other actions in the meantime or even cancel the request that was sent to the server. Using threads can help.

For all activities that require a wait — for example, because of file, database, or network access — a new thread can be started to fulfill other tasks at the same time. Even if you have only processing-intensive tasks to do, threading can help. Multiple threads of a single process can run on different CPUs, or, nowadays, on different cores of a multiple-core CPU, at the same time.

You must be aware of some issues when running multiple threads, however. Because they can run during the same time, you can easily get into problems if the threads access the same data. You must implement synchronization mechanisms.

This chapter provides the foundation you will need when programming applications with multiple threads.

OVERVIEW

A thread is an independent stream of instructions in a program. All your C# programs up to this point ...

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