16 JUN 2019

c#basics flight-center wait-handle auto-reset-event manual-reset-event task

wait1.png

We talked about WaitHandle class in .NET which is used to synchronize between asynchronous work.  Two important classes which derive from WaitHandle are: Manual Rest Event and Auto Rest Event. these classes are used in order to allow one thread to wait in a specific location in the code (WaitOne) until  a different thread completes his work (Signal). it’s quite similar to Wait and Pulse (or PulseAll) but the difference is that you do not need a locking object and you don’t need a critical section. you simply wait-one and signal without any constrains. we made an example in which there are threads which should add drawing to a web page, but they all should wait for the page to be loaded first, before they could start drawing. therefor all of these threads will be in a WaitOne state- till the loading page thread finished and call the Signal. The difference between manual reset event and auto reset event is that in manual reset event- after the signal has occurred- all the threads can pass the WaitOne “gate” (even threads reaching the WaitOne in a later point in time) in oppose to auto reset event, in which only one thread can pass the WaitOne “gate”. it means that we have to call the Signal each time we desire to allow one waiting thread to pass the WaitOne “gate” (similar to Wait-Pulse)

tasks.jpg

We explored the Task type. what is a task?  answer: “A task is an object that represents some work that should be done. The task can tell you if the work is completed and if the operation returns a result, the task gives you the result. Tasks class also let you create threads and run them asynchronously (by default uses the ThreadPool threads)”. we saw how to create tasks, start task, wait for task, retrieve task result, wait for all-tasks, and wait for any task (in a list of tasks)

More topics covered:

  • WaitOne( millisecond)  will proceed after the time limit, even if the “gate” is closed!
  • ManualRestEvent can be set to Signaled in the ctor
  • For non-threadpool use: TaskCreationOption . LongRunning
  • Task Parallel Library (TPL) introduction
  • Tasks uses background thread
  • Cancellation token introduction
  • Task.RunSynchronously 
  • Task.Result
  • Project start-up

Links:

Leave a comment

Design a site like this with WordPress.com
Get started