Dodsworth
asked on
Object Disposed Exception
I'm getting this error...
System.ObjectDisposedExcep tion: Cannot access a closed Stream. at System.IO.__Error.StreamIs Closed() at System.IO.MemoryStream.See k(Int64 offset, SeekOrigin loc)
I haven't disposed of the stream in question.. so who has ?
Are streams cleaned up differently ? The stream in question is defined at class level.
Any ideas?
System.ObjectDisposedExcep
I haven't disposed of the stream in question.. so who has ?
Are streams cleaned up differently ? The stream in question is defined at class level.
Any ideas?
It would help to see the code in question.
ASKER
I've chopped the code down so it's easier to read, which has prompted a thought..
When I dispose of e.ImageStream is mainStream also being disposed because I'm using '=' ?
When I dispose of e.ImageStream is mainStream also being disposed because I'm using '=' ?
Partial Public Class Camera
Private mainStream As Stream 'This is where I'm holding the image stream from the camera
Private saveNow As Boolean = True 'Save the image straight away or on click of save button
Private Sub cam_CaptureImageAvailable(ByVal sender As Object, ByVal e As Microsoft.Devices.ContentReadyEventArgs)
Try
mainStream = e.ImageStream
If saveNow Then
saveImage() 'This call does not error
End If
Catch err As Exception
Stop
Finally
e.ImageStream.Close()
End Try
End Sub
Private Sub saveImage()
mainStream.Seek(0, SeekOrigin.Begin)
library.SavePictureToCameraRoll(Date.UtcNow.Ticks.ToString & ".jpg", mainStream)
End Sub
Private Sub Ok_Click(sender As Object, e As EventArgs)
saveImage() 'Here Errors :(
End Sub
End Class
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thought that might be the case. So I need to copy the e.Imagestream to mainStream somehow?
Or remove the line:
e.ImageStream.Close()
From your Finally clause, and then close the stream when you are done with it (probably in your SaveImage() method.
So I need to copy the e.Imagestream to mainStream somehow?You can use the Clone method for this purpose.
and then close the stream when you are done with it (probably in your SaveImage() method.But you'll also want to include some checking on the state of that variable, in case someone clicks the button twice. I'd suggest setting the variable to Nothing after you close the image, and then add a check for Is Nothing in your save code.
ASKER
It would seem that e.ImageStream goes out of scope outside cam_CaptureImageAvailable.
I tried
'New' cannot be used on a class that is declared 'MustInhert'
So I changed it to
I tried
e.ImageStream.CopyTo(mainStream)
but got a ArgumentNullException which the documentation indicates that is because the destination is Nothing. Private mainStream As New Stream
Resulted in 'New' cannot be used on a class that is declared 'MustInhert'
So I changed it to
Private mainStream As New MemoryStream
And all is well :)