ThreadBox/UIThreadBox


#1

Someone else might find this bit of code useful:

  https://gist.github.com/mikehearn/7274375de2950e10f56f

It’s a simple idea but I find it helps somewhat:  a class with a private field and methods that pass the field to a receiver method whilst holding a lock (or, alternatively, requiring that you be on the UI thread).

The effect is that it’s harder to forget to take a lock because the data you want to access won’t be in scope unless you go via the ThreadBox.

There are obviously two ways to break this guarantee:

  • Nothing stops you from entering the box and then copying the protected reference somewhere else.
  • If you switch thread contexts inside the scope of the box, you still have access to the original data but the lock may not be held.