What is the difference between Tolistasync() and Tolist()?

Asked

Viewed 2,268 times

2

What difference between ToListAsync() and ToList()?

As in the example below, what is the difference between one and the other?

using Modelo.Classes.Contexto;
using System.Data.Entity;
using System.Linq;

namespace AppConsoleTestes
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new dbContexto())
            {
                var ListaUsuario1 = ctx.Usuarios.ToListAsync();
                var ListaUsuario2 = ctx.Usuarios.ToList();
            }
        }
    }
}

2 answers

10


ToListAsync() is the ToList asynchronous. Asynchronous methods can be executed without locking the application’s main execution line. E.g.: in a Winforms application, do not lock the GUI in long operations.

For the method to be executed asynchronously it must be called with await before it and the method that calls it must be marked as async.

If it is used as it shows the question, it will return one Task<T> and you will have to worry on how to solve it. If you use await ctx.Usuarios.ToListAsync() the work of "solve" this Task<T> will be automatic.


I will not give more details about the use of async/await because there’s enough about it on the site.

In C#, what is the await keyword for?

Correct use of async and await in Asp.Net

  • Damn, I was just finishing writing :(

  • 2

    You can post, you have nothing to lose, quite the contrary, if the answer is right, my upvote is guaranteed. This question will serve more people in the future, it is good to have several answers, as long as they are all correct and no copy of the other.

3

The method with Async in the name is asynchronous, ie it has ability to run without locking the current run line, so if it had been called in the correct way soon after its inception the code could already start to the next line, and probably the ToListAsync() would perform in parallel.

In order for the asynchronicity to occur it would actually need a await

Browser other questions tagged

You are not signed in. Login or sign up in order to post.