Create class instance in threads

Asked

Viewed 510 times

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?

2 answers

5


  1. Object instance is object instance. Thread is thread. Except for the fact that a thread is a specific object, one thing has nothing to do with the other.

  2. Threads are finished when no longer being used (usually). Object instances are destroyed when they are no longer useful and C# automatically manages this.

    Note that this is a bit more complicated. The object containing the thread can be collected soon after giving the Start(). He is no longer needed after the thread runs. It runs independently.

    To thread as long as what is contained within it (CriarAnimal) is running. Note that it can run even with the "official" closure of the application, since it put on background.

At the end the displayed code will create a array with 10 animals where each one will go through some process of creation. This process is presumed to be long and the 10 may occur in parallel and concurrently, if you have time :).

And it’s important to understand that threads can slow code down and not bring gains, on the contrary. has great chance of the cost of creating a thread be greater than the cost of creating a Animal.

Understand that it is a technique considered almost obsolete. The use of tasks can help a little minimize the waste of creating thread.

See more or less how it would be a for parallel.

See also: What is the difference between async, multithereading, parallelism and competition?.

According to the comments below, the question has been modified, and indicates that this solution seems less suitable yet.

  • I added the method CriarAnimal in the question, the idea would be that each Animal is a Thread, to create a simulation environment for a work on Thread faculty. The statement I have is Os animais deverão ser implementados como Threads.

  • 2

    Then the question started to change (and that’s not good because my answer started to be invalidated). Implement a Animal as thread does not make sense according to my first statement. Has creation of thread within the thread :-~. To answer by Bruno Costa seems to be going down a better path, but I still don’t know if it’s ideal, he responded on top of what was there.

  • 2

    @bigown It’s true. I also don’t know why the AO is doing it that way. I left a comment in my reply saying that doing multi-threaded in this scenario ends up not bringing many advantages. It was a good response from you

  • @Brunocosta was what I saw even without knowing the CriaAnimal, So I made the point that there’s no gain. I don’t know if they’re teaching in college how to use something for a loss, I find it regrettable. It could be said that the goal is to learn to use thread, but then it would only be to take an example where it would be good its use and that thread is better than Task. This is a case that is possible, but I’m not sure, that no parallelization mechanism is useful.

  • @bigown Yes misspelled. It may be useful to use the Parallell.Foreach for example. What I meant was that having one thread per object turns out to have no advantages in this case.

  • @mustache, I used the Dispatcher.invoke in order to place the images on the screen, because it was giving me the error that Thread could not access another thread...

  • @Meuchapeu this whole code seems wrong. It is mixing the object with screen, everything seems strange to me. Then a mistake is made to fix another error. I can’t even say much because it’s a technique that is not used anymore and with the aggravating of not being useful.

  • @bigown @Bruno Costa, I am a layman in these Thread, I’m trying to do what was asked by the teacher, but I don’t like it either, because each animal being a thread, and user being able to say how many animals he wants... if the user types 1,000 animals, I’ll have 1,000 thread running...

  • @Meuchapeu this user being able to tell the amount is just a question of data entry validation.

  • @bigown, this is what is confusing me, why each animal has to be an object implemented as thread, but I have to show on screen these animals moving around...

  • The solution seems to be different, but then it would need a larger context, without running the risk of being broad :)

  • The job is supposed to be a kind of game, but it’s mixing a lot of things in my opinion...

  • 1

    @Meuchapeu Instead of doing what you were asked to do, you can do it differently and explain to your teacher why you chose to do it that way. Try to see thread-related issues and see what benefits they can bring, as well as problems. The bigown left some questions that touch on the subject. See also the questions related to them. A valid approach is first to do with only one thread, hence Voce thinks a solution with many.

Show 8 more comments

0

What you did was very confusing, but what you want is impossible.

The Thread class is marked with Sealed, meaning it cannot be inherited, so it is not possible to make an Animal Thread (A bizarre creature), and multiple inheritance in c is impossible#.

But you can always make an Animal that has a Thread (an aggregation), so it can have a dynamic behavior (I think that’s what you really want).

This involves having a loop in Thread execution.

Cada Thread criada será uma instancia? ou cada Thread apenas está carregando uma referência de uma instancia?

Thread itself is an object instance of the Thread type, like any other. When you broadcast Start, it starts executing the delegated function you designated and when you finish it closes. This execution does not block your execution flow (usually the Thread of the interaction, but the interface runs on a Thread as well), as you may already know, the Thread is staggered and executed in "parallel" (or time-division, or actually parallel if you have multiple processor cores).

2 - Imaginemos que a classe Animal tem uma propriedade vida, e quando a vida chegar a 0 o Animal deixa de existir ou seja minha instancia/thread são finalizadas/destruídas, como implementar isso?

The delegated function should be something like:

private void LoopAnimal()
{
  while(estaVivo)
  {
    //Executar ações do Animal, detectar colisões, implementar comportamentos etc..
    ExecutarComportamentoDoAnimal();
    if(Vida == 0)
      estaVivo = false;
    //Para você não consumir todo o processador deve esperar algum tempo entre cada iteração, o sistema operacional agenda o retorno a essa tarefa, isso não tem muito boa precisão, se você precisa de alta precisão no tempo pesquise por Multimedia Timer, evite bloquear a Thread pois seu processador vai a 100%
    Thread.Sleep(100);
  }
  //Aqui você pode emitir um evento sinalizando que a Thread terminou, isso é necessário pois a Thread não tem um evento que sinaliza o fim (algo do tipo Thread.Exited)
  AnimalMorreu();
}

You can also use Task, the concept is +/- the same, but internally it has a Thread (which is the lowest level element of parallelism).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.