简体   繁体   中英

C# Re-use or re-create tasks?

I have a while loop in which I create and start tasks, as follows:

while (!stopped)
{
    List<Task> tasks = new List<Task>();

    for (int i = 0; i < 10; i++)
        tasks.add(Task.Factory.StartNew(() => DoSomething(i)));

    Task.WaitAll(tasks.ToArray());
}

Would I get better performance if the tasks are created once before the while loop, and restarted everytime (because the data being passed to the function never changes)?

You can't restart task http://msdn.microsoft.com/en-us/library/dd270682.aspx By the way

Task.Factory.StartNew(() => {....})

is fast than

Task task = new Task(() => {...});
task.Start();

because no locking on Start method.

In your case use async io to get performance boost.

There is nothing fundamentally wrong with your code. This is a perfectly acceptable approach. You do not need to worry about the performance or expensive of creating tasks because the TPL was specifically designed to be used exactly like you have done.

However, there is one major problem with your code. You are closing over the loop variable . Remember, closures capture the variable and not the value . The way your code is written the DoSomething method will not be using the value of i that you think it should. Your code needs to be rewritten like this.

while (!stopped) { List tasks = new List();

for (int i = 0; i < 10; i++)
{
    int capture = i;
    tasks.add(Task.Factory.StartNew(() => DoSomething(capture)));
}

Task.WaitAll(tasks.ToArray());

}

As a side note you could use the Parallel.For method as an alternative. It is definitely a lot more compact of a solution if nothing else.

while (!stopped)
{
  Parallel.For(0, 10, i => DoSomething(i));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM