Hello, fellow Unity Engineers!
We have a published app where Unity Performance Reporting shows we get IOExceptions from FileStream.Dispose(). So now I have two questions.
- How do I properly dispose a FileStream if Dispose() throws an exception?
- Why does the stacktrace not show what is calling FileStream.Dispose()?
Thanks for your help! More details below.
FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate);
fileStream.Write(byteArray, offset, count)
try
{
fileStream.Dispose();
}
catch (IOException)
{
// What should I do here?
}
The following screenshot is from Unity Performance Reporting. Most of the reports are from FileStream.Write() which I can handle properly. But some of them are from FileStream.Dispose() which I do not know how to handle properly. What do I do for Dispose()?
Below is a screenshot of one of the reports. Why does the stacktrace start at FileStream.Dispose()? I suspect the FileStream exists in a class we have called DownloadManager. Why doesn’t DownloadManager appear in the stacktrace?
How should I handle FileStream.Dispose() throwing an exception? Thanks for any advice!
You can Flush the stream manually in the try-catch block before disposing. How should you handle the exception is really up to you. File handle gets disposed of properly even if you get the exception, so no worries here.
Wrap it in a using statement and then you don’t have to call Dispose yourself at all
using (var fileStream = new FileStream(....))
{
fileStream.Write(..);
}
That’s true, but wouldn’t it throw an exception anyway since using is just a try-finally with Dispose called in finally?
It would - but then you could just wrap the using in a try-catch which should nab the exception thrown by Dipose.
Yeah, I’ve read around a bit more and it seems that you can catch the IOException, then rethrow if you need to. In my case, we just tell our background DownloadManager to stop trying to download in the background.
People seem to suggest that I don’t need to worry about releasing any resources, and that the garbage collector will handle whatever resources are left. I’m not sure if there’s any unmanaged code involved or how that works, but I also don’t see any other choice but to accept it’s okay.