02 JUN 2019

c#basics thread-states ThreadPool Monitor lock concurrent-collections

threadstates.PNG

We encountered the dilemma of using multi-threaded solution vs. single threaded solution: are we reducing the execution time or not? … to answer this question we should test how long does it take us to spawn new threads? and if we sum up all of the initialization threads time and the execution time – does it take longer than a single thread? if so- we should use the multi-threaded solution, otherwise we should use a single threaded solution. We learned about the ThreadPool collection and saw that “borrowing” a thread from the ThreadPool saves us a lot of time! since we do not need to initialize the thread (it is automatically ready-to-go). however, we should not use ThreadPool threads for long operations, and also beware not to exhaust this resource.
We saw that multi threaded programming might cause an exception when few threads try to add/remove items from a List. why? because if one thread is trying to add an item to the list, while another thread is trying to remove an item from the list – it crashes the program. What could be the solution?  Answer: (1) use .NET Concurrent collections which are Thread-Safe (meaning that they support multi-thread access). these collections limits the access to a resource for only one thread at a time. it’s an easy-to-use solution but the down side is that we always pay the cost of longer access time (because of the locking mechanism) (2) use Monitor.Enter and Monitor.Exit: these commands block a certain code-block (critical section) and do not allow more than one thread to enter this code-block at the same time. we saw that if we forget to call Monitor.Exit then the lock is not released and a deadlock scenario may occur (causing the thread to get “stuck”). Finally we saw that instead of using Monitor.Enter and Monitor.Exit– we can simply use lock (key) { … }, which “behind the scene” calls the Monitor.Enter and Monitor.Exit (using a try-finally block). still there are some differences between Monitor and lock (i.e. Monitor.TryEnter)

More topics covered:

  • Thread states flow
  • Stopwatch
  • SyncRoot
  • Every object can be used as a key
  • We need different locks for different resources
  • Beware of using instance lock for static resource
  • System.Collections.Concurrent namespace
  • System.Collections.Concurrent.ConcurrentDictionary
  • ArrayList.Synchronized(new List<int>());
  • ThreadPool.QueueUserWorkItem

Links:

Leave a comment

Design a site like this with WordPress.com
Get started