Imagine that I have a class:
Class Animal
{
//Propriedades
}
Now creating multiple instances of the class I do as follows:
Animal[] animais = new Animal[10];
for(int i = 0; i < 10; i++)
{
animais[i] = new Animal();
}
So far, all right, in theory at the end of the execution of the for
method, I will have an array with my 10 instances of class Animal
.
Now I have the following problem:
Each Animal should be a Thread
.
1 - How can I implement this? so that each instance of my class is a Thread
?
What I did, and I'm not sure it's correct ...
public void ThreadAnimal()
{
Thread th;
Animal[] animais = new Animal[10];
for (int i = 0; i < 10; i++)
{
animais[i] = new Animal();
th = new Thread(new ParameterizedThreadStart(CriarAnimal));
th.SetApartmentState(ApartmentState.STA);
th.IsBackground = true;
th.Start(animais[i]);
}
}
public void CriarAnimal(object obj)
{
Dispatcher.Invoke(() =>
{
var animal = obj as Animal;
var img = new Image()
{
Source = animal.Img,
Tag = animal,
Width = 32,
Height = 32,
};
double posX = _canvas.ActualWidth - img.Width;
double posY = _canvas.ActualHeight - img.Height;
Canvas.SetLeft(img, rnd.NextDouble() * posX);
Canvas.SetTop(img, rnd.NextDouble() * posY);
_canvas.Children.Add(img);
});
}
Will every% created% be an instance? or every Thread
is only loading a reference from an instance?
2 - Let's say that the class Thread
has a property Animal
, and when vida
reaches vida
0
ceases to exist or is my / are finalized / destroyed, how do I implement this?