Posts

CancellationToken and Thread.Sleep

I have a task that, when some condition occur, sleeps for a few seconds. Most of the time, the task does some heavy processing, so I can't use a thread timer. The problem with the sleep is that, whenever I cancel the task using the CancellationToken(Source), I have to wait for the sleep to finish before the task finishes. The Thread.Sleep doesn't have any CancellationToken parameter. while (token.IsCancellationRequested ==  false ) {      // Initial processing      if  ( someCondition ==  true  )     {          // Sleep for 5 seconds          Thread .Sleep(5000);     }           // Continue processing } The solution is quite simple - use the cancellation token's wait handle: while (token.IsCancellationRequested ==  false ) {      // Initial processing      if  ( someCondition ==  true  )     {          // Sleep for 5 seconds, but exit if token is cancelled          var  cancelled = token.WaitHandle.WaitOne(5000);          if  ( cancelled )             

Clean code with defensive programming technique

A lot of bugs is introduced because software developers often make assumptions about the input. I will show you a technique that will make your code more robust and easier to maintain. The customer wants a function that can adjust product prices with a percentage value in the range 1%-30%. Check this function: ///   <summary> ///  Adjusts product prices ///   </summary> ///   <param name= "products" > Array of products </param> ///   <param name= "percentage" > The price adjustment percentage (valid range = 1 to 30) </param> public   void  AdjustPrice( IEnumerable < Product > products,  double  percentage) {      foreach  ( var  product  in  products)         product.Price *= (1d + percentage / 100d); } There are some problems with this code. First, the developer assumes that the input will always be correct - that the caller will always provide an array of products and a percentage within the valid range. Thi