When are threads (Thread Pool) initialized? - C#

Asked

Viewed 486 times

3

I have the following code:

public void mainFunc()   {
    for (int i = 0; i < 10; i++)
    { 
        ThreadPool.QueueUserWorkItem(new WaitCallback(funcThread), pto);
    }
    Thread.Sleep(2000) // Thread de teste.
    // Fazer algo quando todas as funcThread chegarem ao fim.
    // .....
    // Form4.doSomething()
}

I mean, I want the funcThread be created 10 times and after all 10 functions come to an end, I want to do a routine that calls another Form. What happens is that first he executes all that is in mainFunc and only then does he do what is in threads.

I’ve tried putting one Thread.Sleep 2 seconds, but not at all. He lets the two seconds go by, does what he has to do in form4 and only then advances to the 10 threads...

'Cause that’s how I do the ThreadPool.QueueUserWorkItem(new WaitCallback(funcThread),pto) the program doesn’t start running threads right away, but only after mainFunc is finished? Thank you

1 answer

3


When we talk about manipulating C#threads, we recommend using the Task Parallel Library (TPL), which is a higher-level API for manipulating the application’s Threadpool. Nor am I the one saying this: the own Microsoft is who recommends because they realized how complicated it was to control some things through the original library:

In Conclusion, I’ll reiterate what the CLR team’s Threadpool Developer has already stated:

"Task is now the Preferred way to Queue work to the thread pool."

Anyway, when using a Queueuserworkitem, you are suggesting that when any Thread remains, it will perform a certain method. The problem is that this way, we have no control over when it will occur.

Through the TPL, we basically have the Task class that represents an asynchronous operation that may or may not have been done yet. Thus, in the example below, I have the TPL perform 10 times an operation and save the Tasks reference to control its executions:

// utilizei um clique de botão só para testar, tanto faz aqui
private async void button1_Click(object sender, EventArgs e)
{
    // só porque você definia ele como parâmetro do seu método
    int pto = 0;

    var taskList = new List<Task>();

    for (int i = 0; i < 10; i++)
    {
        // manda enfileirar no ThreadPool pra executar o seu método
        var task = Task.Run(() => { funcThread(pto); });

        // adiciona na lista a referência a cada Task criada
        taskList.Add(task);
    }

    // manda esperar que todas as Tasks referenciadas terminem para que o programa continue
    Task.WaitAll(taskList.ToArray());

    // espera uns 5 segundos só pra vermos o output confirmar o teste
    await Task.Delay(5000);

    // chama o seu form sem problemas
    Console.WriteLine(String.Format("{0} - Form4.doSomething()", DateTime.Now));
}

public void funcThread(int pto)
{
    Console.WriteLine(String.Format("{0} - funcThread", DateTime.Now));
}

The output of my example:

09/02/2016 23:48:55 - funcThread
09/02/2016 23:48:55 - funcThread
09/02/2016 23:48:55 - funcThread
09/02/2016 23:48:55 - funcThread
09/02/2016 23:48:55 - funcThread
09/02/2016 23:48:55 - funcThread
09/02/2016 23:48:55 - funcThread
09/02/2016 23:48:55 - funcThread
09/02/2016 23:48:55 - funcThread
09/02/2016 23:48:55 - funcThread
09/02/2016 23:49:00 - Form4.doSomething()

Observing: I only used async/await in the method to hold for 5 minutes, it is not really necessary that your method be marked as asynchronous for the Task Waitall.() work

Browser other questions tagged

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