O'Reilly logo

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

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

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