简体   繁体   中英

C# - Monogame - Program still uses an image after setting it to null

Okay so basically I want to load an image (check), use it (check), unload it(semi-check) and then load it again (fail)...

So here is what I did:

TileTexture = Texture2D.FromStream(GraphicsDevice, new System.IO.FileStream(tileTextureName, System.IO.FileMode.Open));

It load a textuure, works fine, I can draw it no problem, then when I don't want to use it I set it to null

this.TileTexture = null; 

and it works fine, image dissapears, and I am able to load some other image from anywhere on my computer again (and then that image is put into that Texture2D variable where the previous one was), but when I want to load the image I used before again, even though now another image is stored in that Texture2D variable, I get an exception:

The program cannot acces the file because it is being used by another process. (Which would be my program).

How do I then completly stop my Monogame program from using this image so I can acces it again at the same runtime if maybe I would need to ?

You need to close your stream when you are done with it. Instead of this:

TileTexture = Texture2D.FromStream(GraphicsDevice, new System.IO.FileStream(tileTextureName, System.IO.FileMode.Open));

Try:

using (var fs = new System.IO.FileStream(tileTextureName, System.IO.FileMode.Open))
{
    TileTexture = Texture2D.FromStream(GraphicsDevice, fs);
}

using will take care of closing and disposing the stream

You are calling a new steam on your method call:

new System.IO.FileStream(tileTextureName, System.IO.FileMode.Open))

Instead, place it in a var and then call the .Close method

var stream = new System.IO.FileStream(tileTextureName, System.IO.FileMode.Open)
...
stream.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM