What are the pros and cons of the TaskListObject implementation on ListObject

5

What are the advantages between the two implementations below. Both return a list with several products (more than 1k):

public Task<List<Product>> GetAllProductsAsync()
{
    var query = Products.ToList();

    return Task.FromResult(query);
}

X

public List<Product> GetAllProducts()
{
    var query = Products.ToList();

    return query;
}
    
asked by anonymous 01.08.2015 / 16:26

1 answer

7

The first one is prepared to do this asynchronously, that is, the code starts to do and continues "normal" life regardless of the execution of this query and when it finishes, the code will be warned of this .

In the past this was tricky to do in C #, though feasible. With C # 5 it got a lot easier because the compiler mounts the state machine that controls this flow. And the Task class helps in this by controlling whether or not this will run in separate thread . Although in the current form it is not suitable for applying asynchronicity since the async modifier is missing in the method.

When you want to perform the task asynchronously, you must do this through a class that represents a task, that is, a Task . Then you will receive a task that will contain the result at the right time, rather than pure result.

Obviously asynchronous execution has the advantage of not blocking the application. If it takes too long to generate this list, the application will continue running normally and will resume there when the list is generated. The second method will block execution until the list finishes generating.

The size is not important, but the time it will take to complete the task. It is often said that if the task takes less than 50ms, it is better to run synchronously anyway, after all, asicronicity has its cost.

Except this case of the task being very fast I only see advantages in using the asynchronous form. Of course the code gets a bit more complex, but it's minimal. What you can really mess up is if you need to debug. But the ideal is to make it work well synchronously first, this avoids a little of the problem. Of course, if you have problems debugging the process of asynchronicity, you're really flushed. But it has improved with Visual Studio 2015. Debugging asynchronous tasks can be more cumbersome and confusing under certain circumstances.

Eventually using ToListAsync() might be interesting there. But it depends on how this method will be used and what this ToList() current is doing. It's just a guess.

To learn more about the feature, see this question . I gave an answer there that illustrates well the operation. You have other answers with different approaches that will help you asynchronicity. Another very good question with more focus on ASP.Net can be seen here.

As a matter of curiosity, I do not know if it was just an example but the variable is totally unnecessary in this method.

    
01.08.2015 / 16:56