Create a Task list, with tasks without executing

Posted by Ernesto Araya Eguren on Stack Overflow See other posts from Stack Overflow or by Ernesto Araya Eguren
Published on 2013-10-27T09:49:22Z Indexed on 2013/10/27 9:53 UTC
Read the original article Hit count: 239

Filed under:
|
|
|
|

I have an async method

private async Task DoSomething(CancellationToken token)

a list of Tasks

private List<Task> workers = new List<Task>();

and I have to create N threads that runs that method

public void CreateThreads(int n)
{
    tokenSource = new CancellationTokenSource();
    token = tokenSource.Token;
    for (int i = 0; i < n; i++)
    {
        workers.Add(DoSomething(token));
    }
}

but the problem is that those have to run at a given time

public async Task StartAllWorkers()
{
    if (0 < workers.Count)
    {
        try
        {
            while (0 < workers.Count)
            {
                Task finishedWorker = await Task.WhenAny(workers.ToArray());
                workers.Remove(finishedWorker);
                finishedWorker.Dispose();
            }
            if (workers.Count == 0)
            {
                tokenSource = null;
            }
        }
        catch (OperationCanceledException)
        {
            throw;
        }
    }
}

but actually they run when i call the CreateThreads Method (before the StartAllWorkers). I searched for keywords and problems like mine but couldn't find anything about stopping the task from running. I've tried a lot of different aproaches but anything that could solve my problem entirely. For example, moving the code from DoSomething into a workers.Add(new Task(async () => { }, token)); would run the StartAllWorkers(), but the threads will never actually start.

There is another method for calling the tokenSource.Cancel().

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading