3
Imagine 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 so good, in theory at the end of the execution of the method for
I’ll have a array with my 10 instances of the class Animal
.
Now I have the following problem:
Each Animal shall be one 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 right...
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);
});
}
Each Thread
created will be an instance? or each Thread
is just loading a reference from an instance?
2 - Let’s imagine that the class Animal
has a property vida
, and when the vida
come to 0
the Animal
ceases to exist or is my instance/thread are finalized/destroyed, how to implement this?
O AO made a very similar question earlier
– Bruno Costa