flibitijibibo/FNA — pull request #272 by elisee (2014-12-30 16:25:18+00:00)
Title: Race condition leads to NullReferenceException in Texture2D.Dispose

Context: In my XNA app, I'm downloading the user's friends' user pictures from the Internet and as soon as I get one of them, I use ``Texture2D.FromStream`` to load it. (I'm not on the main thread at that point, I'm in a HttpWebRequest response callback, which is important to trigger the bug.)

If a user has lots of friends, this happens a lot during the first few seconds and leads to a crash if the user decides to close the app while pictures are still being set up.

----

When creating a ``Texture2D`` with ``Texture2D.FromStream``, there's a small amount of time where ``Texture2D.texture`` is null, between the constructor getting called and the ``ForceToMainThread`` callback actually happening (https://github.com/flibitijibibo/FNA/blob/7c626f3b043f82c5afd858f569de9398fd5db0f9/src/Graphics/Texture2D.cs#L81)

If the app is closed before ``Texture2D.texture`` has been set, ``Game.Dispose()`` will trigger ``Texture.Dispose`` (https://github.com/flibitijibibo/FNA/blob/7c626f3b043f82c5afd858f569de9398fd5db0f9/src/Graphics/Texture.cs#L53) which does:

Game.Instance.GraphicsDevice.GLDevice.DeleteTexture(texture);

with a null ``texture``.

I fixed it with a simple null check right before calling ``DeleteTexture``.