Domanda

In the method below what is the difference between using

ListThreads.Add(new Task(() => item.Execute()));

and

ListThreads.Add(new Task(item.Execute));

private void Execute()
{
    for (int i = 0; i < ThreadNumber; i++)
    {
        ListObjects.Add(new MyClass(i + 1, ThreadNumber));
    }
    foreach (MyClass item in ListObjects)
    {
        ListThreads.Add(new Task(() => item.Execute()));
        ListThreads[ListThreads.Count - 1].Start();
    }
    Task.WaitAll(ListThreads.ToArray());
}
È stato utile?

Soluzione

You ask the difference between

() => item.Execute()

and

item.Execute

The former is a lambda that calls item.Execute. The, item.Execute, is a method group. When they are passed to the constructor of Task they are both converted to a delegate of type Action.

There is quite a difference though. The lambda captures the variable item. And the method group does not. This means that when the lambda is executed, the value of the variable item may be different from its value when you passed the lambda to the constructor of Task.

To make the lambda version equivalent to the method group version you could introduce a local variable:

foreach (MyClass item in ListObjects)
{
    MyClass tmpItem = item;
    ListThreads.Add(new Task(() => tmpItem.Execute()));
    ListThreads[ListThreads.Count - 1].Start();
}

Do note that the language has been modified between C# 4.0 and C# 5.0. In C# 5.0 the code in your question behaves in exactly the same way as does the code above in this answer. For more details see:

Altri suggerimenti

First of, it's a bad idea to use foreach variable in lambda expression. So, in this particular case the correct way is to write ListThreads.Add(new Task(item.Execute));

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top