Start multiple threads in a repeat command

Asked

Viewed 634 times

1

I have a project where I need to start 30 times a thread which will run the same method, and wanted to do this in a repeat command, for example:

    for (int i = 0; i < 30; i++)
    { 
       Thread t = new Thread(MetodoVoid); 
       t.Start();
       System.Threading.Thread.Sleep(1000);
    }

But when I wear it says thread is already running and error, how to proceed?

  • 1

    Read this: http://answall.com/q/1946/101 See if something more abstract doesn’t solve it better for you. There’s little reason to use it today thread raw: http://answall.com/q/77759/101 and http://answall.com/q/2793/101 See also: http://answall.com/q/86014/101 Also: http://answall.com/q/112357/101

  • 1

    This code works perfectly: https://dotnetfiddle.net/UCXSRv. Error elsewhere.

2 answers

3


You are playing everything in one variable. If you want to insist on this form, you have to play elements of a array or list, so each thread will be in a variable.

But read my comment. If you’re wrong about something so simple, you shouldn’t use something that’s so complicated to do right.

var threads = new List<Thread>();
for (int i = 0; i < 30; i++) { 
   threads.Add(new Thread(MetodoVoid)); 
   threads[i].Start();
}

I put in the Github for future reference.

  • I know where my mistake is, I put that code just to illustrate what I want

  • I thought of creating an array or a list, but I haven’t been able to apply it yet

  • Ahahaha solved! thank you very much man =]

  • 1

    @That doesn’t make sense. In its original code, with each loop iteration the variable receives a new instance of Thread, and Start occurs in this new instance - it will not give thread error already in use because it is not referencing the same thread. Your error was elsewhere and not in the reuse of the variable. The array is not solving anything there. There is no "throw everything into a single variable" - a variable can only have a single value (in this case, the value of the variable is a reference to the newly instantiated thread). See your original code working ok: https://dotnetfiddle.net/UCXSRv

  • The error is that Métodovoid had not finished before starting again, and I wanted them to work simultaneously, so it gave the error.

0

List<Thread> lst = new List<Thread>();

for (int i = 0; i < 30; i++)
{
   lst.Add(new Thread(MetodoVoid));
}

lst.ForEach(t => t.Start());
  • has how to put a Sleep in this lambda?

  • I’m not sure in this case, so I suggest you do a conventional foreach.

  • Put a Sleep after the Start()? @Luísmiguel

  • yeah, like that...

Browser other questions tagged

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