8 Processing a sequence of items in the background

 

This chapter covers

  • Processing items in parallel
  • Performance characteristics of different ways to run code in parallel
  • Processing items sequentially in the background
  • Background processing of important jobs

There are three primary reasons for using multithreading in everyday applications. The first, and the most common, is when an application server needs to manage requests from multiple clients simultaneously. Typically, this is handled by the framework we use, such as ASP.NET, and it is beyond our control. The other two reasons for using multithreading are to finish processing sooner by performing parts of the processing in parallel and to push some tasks to be run later in the background. Both of these can significantly improve your program performance (or, at least, responsiveness and perceived performance). Let’s begin by discussing the first reason: completing our processing faster.

8.1 Processing items in parallel

To demonstrate parallel processing, we will write the world’s simplest mail merge software. Mail merge is a process that takes a mail template and creates an individual customized message for each recipient by replacing tokens in the template with information about the recipient.

8.1.1 Processing items in parallel with the Thread class

8.1.2 Processing items in parallel with the thread pool

8.1.3 Asynchronously processing items in parallel

8.1.4 The Parallel class

8.2 Processing items sequentially in the background

8.2.1 Processing items sequentially in the background with the Thread class

8.2.2 The work queue pattern and BlockingCollection

8.2.3 Processing important items with persistent queues

Summary