Chapter 12. Improving Performance and Scalability with Multitasking

This chapter is about allowing multiple actions to occur at the same time to improve performance, scalability, and user productivity.

In this chapter, we will cover the following topics:

  • Understanding processes, threads, and tasks
  • Running tasks asynchronously
  • Synchronizing access to shared resources
  • Implementing multitasking for a GUI

Note

The Implementing multitasking for a GUI section requires Visual Studio 2017 on Windows 7 or later.

Understanding processes, threads, and tasks

A process, for example, each of the console applications we have created has resources allocated to it, such as memory and threads. A thread executes your code, statement by statement. By default, each process only has one thread, and this can cause problems when we need to do more than one task at the same time.

Windows and most other modern operating systems use preemptive multitasking, which simulates the parallel execution of tasks. It divides the processor time among the threads, allocating a "time slice" to each thread one after another. The current thread is suspended when its time slice finishes. The processor allows another thread to run for a time slice.

When Windows switches from one thread to another, it saves the context of the thread and reloads the previously saved context of the next thread in the thread queue. This takes time and resources.

Threads may have to compete for, and wait for access to, shared resources, such as variables, files, and database objects.

Depending on the task, doubling the number of threads (workers) to perform a task does not halve the number of seconds the task will take. In fact, it can increase the duration of the task, as pointed out by the following tweet:

Understanding processes, threads, and tasks

Tip

Good Practice

Never assume that more threads (workers) will improve performance.

Run performance tests on a base line code implementation without multiple threads, and then again on a code implementation with multiple threads.

Run performance tests in a staging environment that is as close as possible to the production environment.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.170.239