A while ago, I ran into a problem while using DotNet variables.
Whenever I executed the code in our development environment, the code executed without problems, however, on the client side, we received errors when reading the information out of the DotNet objects.
Everybody who has ever worked with .NET will have heard about disposing objects and the Garbage Collector. It is only logical that DotNet within NAV gets disposed as well.
In my setup, I called function in another CodeUnit. This function had a local DotNet Stream variable. The variable was in the function loaded into a StreamReader which was passed around as a parameter.
* Call OtherCodeUnit.DoSomething(StreamReader);
* Do something with StreamReader
* Function DoSomething(VAR StreamReader DotNet.....)
* Local Stream
* StreamReader := StreamReader.StreamReader(Stream);
I always received an error when reading the StreamReader that I could not access a closed stream. And I was certain that I did not close the stream.
Apparently on the client side, the dispose had already fired, causing the stream to be gone (no longer in memory) and the StreamReader was merely pointing to the reference in memory of the stream.
This caused the Stream to actually be closed.
I have no idea what client side setting could cause different behavior on our DEV side and the customer side. The NAV Client version was the same…
Anyway, there is a way to make sure your object does not get disposed too soon.
Whenever you make a DotNet Variable local, parameter (not global) you have an extra Property: SuppressDispose.
When you set this to Yes, the object remains in memory, allowing to read my StreamReader in my case.
I suspect the dispose will then only happen when the code is finished, and not when the variable goes out of scope.