Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, September 22, 2022

C# - Debugging Deadlock

Basic

See https://michaelscodingspot.com/c-deadlocks-in-depth-part-1/

Tips

  1. Use dedicated lock object
  2. Keep lock object private inside a single class and do NOT pass it around outside
  3. Avoid triggering event from inside a lock

Wednesday, September 21, 2022

C# - Dispose Rule

Tips

  1. All IDisposable objects must be disposed. There are only few exceptions e.g. https://stackoverflow.com/questions/38784434/how-to-properly-dispose-the-stream-when-using-streamcontent
  2. Use "using" by default for all IDisposable classes. If "using" cannot be used, at least "try ... finally" must be used and dispose inside "finally".
  3. If a method returns an IDisposable classes, it is the responsibility of the caller to dispose it properly.
  4. Try to keep IDisposable objects lifetime as short as possible e.g. Bitmap

Tuesday, September 20, 2022

C# - Lock Rule

Tips

  1. In each class, lock every public methods and any methods triggered by event from other classes.
  2. For each methods, lock the entire code from start until the end of method by default. Reducing the lock coverage to only certain part of code in a method can be done carefully after this as an optimization.
  3. Triggering event should not be performed from inside a lock.