How to use a static property that implements IDisposable?

As an example:

using (Brushes.Black) { ... } 

not a good idea, because it is static. The next time your application uses Brushes.Black, you will have problems because it has been removed.

Now, if you use Brushes.Black, then you probably should not destroy it, because you will leave one unmanaged resource (I hope!) lying around.

But in general, should you avoid using a lot of static IDisposables or is there something that I am missing?

+4
source share
2 answers

Usually just use them and let the framework class worry about their disposal.

They are there so you can use them without creating or deleting them every time. Each of them is created upon its first use and is cached in a hash table. The framework class is responsible for correctly placing them when the application is closed.

There are actually not many static IDisposables that you need to worry about. If you used a huge number of brushes, you probably would have created them from color in a loop (and then, of course, you are responsible for removing them).

+3
source

As an example:

using (Brushes.Black) {...}

not a good idea because it is static. The next time your application will use Brushes.Black, you will have problems because they are located.

This is not just a static field. The property actively runs code to create new instances if necessary. Look at the corresponding code (reflector):

 public static Brush Black { get { Brush brush = (Brush) SafeNativeMethods.Gdip.ThreadData[BlackKey]; if (brush == null) { brush = new SolidBrush(Color.Black); SafeNativeMethods.Gdip.ThreadData[BlackKey] = brush; } return brush; } } 
+2
source

Source: https://habr.com/ru/post/1286245/


All Articles