Search code examples
.netvb.netweb-servicesstreamwindows-store-apps

Close MemoryStream created on webservice from application


The problem

I am working on a windows tablet application which needs to have access to images from a server. To do so I have a VB.NET web-service with access to the folders containing the pictures.

Once I have transferred the MemoryStream and created the pictures locally, I try to dispose of the stream but it doesn't seem to work. I know this because it takes around 20 minutes for the pictures on the server to be liberated (I can't delete them before that time has elapsed)

How I proceed

This is the method which is on my web-service allowing me to browse through the pictures and get them into MemoryStreams

    Function Execute(TypeOfPictures As String) As List(Of MemoryStream)
        Dim PicturesinDirectory As List(Of String) = Directory.GetFiles("Path").ToList()

        Dim bmp As Bitmap
        Dim lstStreamsToSend As List(Of MemoryStream) = New List(Of MemoryStream)
        For i = 0 To PicturesinDirectory.Count - 1
            'Get the image from file using the path stored in PicturesinDirectory(i)
            bmp = Image.FromFile(PicturesinDirectory(i))

            'Affect the memorystream
            Dim memory As MemoryStream = New MemoryStream()
            bmp.Save(memory, ImageFormat.Jpeg)
            memory.Position = 0

            lstStreamsToSend.Add(memory)
        Next
        Return lstPicturesToSend

    End Function

And the code on the client

Dim service As New ServiceReference1.Service1Client(ServiceReference1.Service1Client.EndpointConfiguration.BasicHttpBinding_IService1)
Dim rcv = Await service.GetPicturesAsync(_folderName)

For i = 0 To rcv.Count - 1
    'Here I save each picture locally using the stream

    'I then try to dispose of the stream
    rcv(i).Dispose()
Next

Limitations

  1. I can't close the stream on the service as it stops me from writting with it on the client later on

  2. I can't test this locally because the pictures are freed instantly (no problem) when the service is local and not published on the web. This forces me to wait 20 minutes between each test or ask my boss to restart the service which is impossible.

The question

Being unable to use the using block to dispose and close the stream properly how do I do it in an Application/Web-Service environment ?

Am I doing something wrong or missing something important ?


Solution

  • The object on the client is independent of any object that's in the server process. Closing anything on the client cannot affect the server. rcv(i).Dispose() does nothing.

    Your resource leak is bmp. Actually, you probably should use File.ReadAllBytes. Why re-encode the picture?

    The 20min timeout probably is IIS shutting down the idle server.