22 Task Synchronization

What’s In This Chapter?

  • Threading issues
  • The lock Keyword
  • Synchronization with Monitor
  • Mutex
  • Semaphore and SemaphoreSlim
  • ManualResetEvent, AutoResetEvent, and CountdownEvent
  • Barrier
  • Reader Writer Lock
  • Timers

Wrox.com Code Downloads for This Chapter

The wrox.com code downloads for this chapter are found at www.wrox.com/go/professionalcsharp6 on the Download Code tab. The code for this chapter is divided into the following major examples:

  • ThreadingIssues
  • SynchronizationSamples
  • SemaphoreSample
  • EventSample
  • EventSampleWithCountdownEvent
  • BarrierSample
  • ReaderWriterLockSample
  • WinAppTimer

Overview

Chapter 21, “Tasks and Parallel Programming,” explains using the Task and Parallel classes to create multithreaded applications. This chapter covers synchronization between multiple processes, tasks, and threads.

It is best when you can avoid synchronization by not sharing data between threads. Of course, this is not always possible. If data sharing is necessary, you must use synchronization techniques so that only one task at a time accesses and changes the shared state. In case you don’t pay attention to synchronization, race conditions and deadlocks can apply. A big issue with these is that errors can occur from time to time. With a higher number of CPU cores, error numbers can increase. Such errors usually are hard to find. So it’s best to pay attention to synchronization from the beginning.

Using multiple tasks is easy as long as they don’t access the same ...

Get Professional C# 6 and .NET Core 1.0 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.