简体   繁体   English

C#重用还是重新创建任务?

[英]C# Re-use or re-create tasks?

I have a while loop in which I create and start tasks, as follows: 我有一个while循环,可在其中创建和启动任务,如下所示:

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)? 如果在while循环之前创建一次任务,然后每次都重新启动(因为传递给函数的数据永远不会改变),我会得到更好的性能吗?

You can't restart task http://msdn.microsoft.com/en-us/library/dd270682.aspx By the way 您不能重启任务http://msdn.microsoft.com/en-us/library/dd270682.aspx

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

is fast than

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

because no locking on Start method. 因为没有锁定Start方法。

In your case use async io to get performance boost. 在您的情况下,请使用async io来提高性能。

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. 您无需担心创建任务的性能或成本,因为TPL是专门为完全按照您的使用目的而设计的。

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 . 请记住,闭包捕获变量而不是value The way your code is written the DoSomething method will not be using the value of i that you think it should. 代码的编写方式DoSomething方法不会使用您认为应该的i值。 Your code needs to be rewritten like this. 您的代码需要像这样重写。

while (!stopped) { List tasks = new List(); while(!stopped){列表任务=新的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. 附带说明一下,您可以使用Parallel.For方法作为替代方法。 It is definitely a lot more compact of a solution if nothing else. 如果没有别的,那肯定是解决方案的紧凑得多。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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