What is the difference between ToListAsync () and ToList ()?

2

What is the 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();
            }
        }
    }
}
    
asked by anonymous 05.12.2016 / 15:52

2 answers

7

ToListAsync() is ToList asynchronous. Asynchronous methods can be executed without crashing the application's main thread. Eg in a WinForms application, do not hang the GUI on long operations.

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

If it is used in the way that the question shows, it will return a Task<T> and you will have to worry about how to solve it. If you use await ctx.Usuarios.ToListAsync() the work to "solve" this Task<T> will be automatic.

I will not give more details about using async / await because you already have a lot on it on the site.

In C #, what is the keyword await?

Usage correct async and await in Asp.Net

    
05.12.2016 / 16:02
2

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

For asynchronicity to occur, in fact, you would need a await

    
05.12.2016 / 16:06