Neverbirth
Neverbirth

Reputation: 1042

Correct CryptoAPITransform use? Memory leak

I've ported an old piece of unmanaged code that used Crypto API to 100% managed .NET code. The code used DES algorithm, and had to maintain it for several reasons.

Since the CryptoAPITransform instances got from the CreateDecryptor and CreateEncryptor methods are marked as reusable, I thought of just creating an instance of them and use them whenever needed.

It seems the code worked, but it was causing memory leaks, so decided to create and dispose an instance each time. So far it seems to not leak, but I'd like to know if I've been using it wrong before, and if so, if I could reuse the instances.

The app is multi-threaded, and makes a lot of operations at the same time, so there could be threading issues, although I wasn't able to find any exception or corrupted message. Also, all my operations were made by calling TransformFinalBlock. Does this sound right to you? Testing the app is tedious, but I guess I'll try for myself if synchronising the threads stops the leaking by any chance.

Upvotes: 2

Views: 228

Answers (1)

Chris Shain
Chris Shain

Reputation: 51329

It was most likely a threading-related bug. From the documentation on CryptoAPITransform:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

I can't stress enough how important it is to look at the "Thread Safety" documentation for all of the classes whose instances you are sharing among threads.

My guess is that in this case the class's implementation relies on some state to correctly use/dispose unmanaged code, and by using them in multiple threads you were causing a failure to dispose these properly.

All of that is a guess of course. I don't know how this class is implemented internally.

Upvotes: 2

Related Questions