C# / XNA - Load objects to the memory - how it works?

后端 未结 3 1930
渐次进展
渐次进展 2021-01-12 08:20

I\'m starting with C# and XNA. In the \"Update\" method of the \"Game\" class I have this code:

t = Texture2D.FromFile( [...] ); //t is a \'Texture2D t;\'
         


        
3条回答
  •  庸人自扰
    2021-01-12 08:56

    The Update Method should not be used to load Textures because it's loaded a lot. In .net, objects are garbage collected, which means that you can't explicitly free an object (even .Dispose doesn't do that).

    If the system is under a lot of pressure, GC may not run as often as it could.

    In short: You are "leaking" thousands of Texture2Ds.

    The proper way to load them is in one of the Initialization Events and store them in a class variable, Dictionary, List or whatever structure. Basically, load it only once and then reuse it.

    If you have to load a texture on-demand, only load it once and store it in the List/Dictionary/Class Variable and again reuse it.

    Edit: Your approach of "Load Image, Release, Load, Release" won't work in .net, simply because you can't explicitly free memory. You could call GC.Collect, but that a) doesn't guaratee it either and b) GC.Collect is incredibly slow.

    Is there a specific reason why you have to reload the image 60 times a second? If you only need to reload it every second or so, then you can use elapsedGameTime to measure the time expired since the last .Update and if it's more than your threshold, Reload the image. (You need a Class Variable like "LastUpdated" against which you compare and which you update when you reload the image)

提交回复
热议问题