Introduction
This program demonstrates how to use threading to load images/textures etc., in a background thread. The program initially only loads the images it requires just to get started. Thus, the program will load faster, and whilst the program is executing, the background thread will continue to load the remaining images.
Background
This program originated in an attempt to load and display textures into a cube using DirectX. The problem I faced was that the program was taking some time to load all the textures at the start of the program (as the program started to display the cube only after all the textures were loaded). To solve this problem, now the program will only load the first set of textures, and once that is done, a thread is started to load the remaining textures. As the thread executes in the background, the main program starts running and displays the first set of textures, significantly reducing the program startup time.
Using the Code
All the code of this program is in FormMain.cs. The two functions that are of interest are:
private void LoadTexture()
private void ThreadFunction()
The function LoadTexture()
is called at startup from InitializeDevice()
.
private void LoadTexture()
{
Bitmap testImage = null;
try
{
for (int count = 0; count < numberOfFaces; count++)
{
testImage =
(Bitmap)Bitmap.FromFile(@"..\..\textures\sky" + count + ".jpg");
texture[0, count] =
Texture.FromBitmap(device, testImage, 0, Pool.Managed);
}
Console.WriteLine("skies loaded");
currentTextureLoadingStatus = 1;
Thread backgroundLoader =
new Thread(new ThreadStart(ThreadFunction));
backgroundLoader.Start();
}
catch
{
MessageBox.Show("Failed loading initial set of textures");
}
}
In the above code, you will notice that we are first loading the initial set of textures and then proceeding to start the new thread.
ThreadFunction()
will load the remaining textures...
private void ThreadFunction()
{
Bitmap testImage = null;
int count = 0;
try
{
for (count = 0; count < numberOfFaces; count++)
{
testImage =
(Bitmap)Bitmap.FromFile(@"..\..\textures\sphere" + count + ".jpg");
texture[1, count] =
Texture.FromBitmap(device, testImage, 0, Pool.Managed);
}
currentTextureLoadingStatus = 2;
Console.WriteLine("spheres loaded");
}
catch (Exception ex)
{
Console.WriteLine("Error Error ! ");
}
}
Running the Program
To change to a different set of textures, use the spacebar on the keyboard. Thus, every time you press the spacebar, the program will go to the next set of textures, if it is already loaded by the background thread. If the background thread has not yet loaded the next texture set, the program will continue displaying the current texture set.
Points of Interest
This program was coded referencing several online tutorials such as:
The textures were obtained from:
The threading code is mine, original :)