When should I use async / await and when not?

1

I am working with the Entity Framework with ASP MVC and I have the following question, should I always use asynchronous methods? or what should I use to choose between one and the other?

Asynchronous

private static async Task AddStudent()
{
   Student myStudent = new Student();
   using (var context = new SchoolDBEntities())
   {           
      context.Students.Add(myStudent);
      await context.SaveChangesAsync();           
   }
}

Synchronous

private static void AddStudent()
{
   Student myStudent = new Student();
   using (var context = new SchoolDBEntities())
   {           
      context.Students.Add(myStudent);
      context.SaveChanges();           
   }
}
    
asked by Juan Salvador Portugal 09.10.2018 в 16:09
source

1 answer

4

You should use async / await when you have a task that takes considerable time and you should wait for it to end. They are usually processes that involve Input / Output operations and the compiler generates a finite state machine when invoking them. If your program does not need to wait for the result of a complex operation, then you can use a traditional synchronous approach since it will run independently.

In your example, if when saving student information you want to show those changes immediately you should use the asynchronous approach, otherwise you will not know if the student object has been saved or not on disk since it is difficult to know if the operation Write will be executed immediately, obtaining information not updated in the next data load. If on the contrary you do not mind showing / using the data immediately after invoking the save method you can undoubtedly use the synchronous method.

To make it understand better we write the following example:

public async Task MetodoAsincronoPrincipal()
{
    // aqui hacemos los cambios al objeto student
    Task<int> tareaLarga= SaveChangesAsync();
    // El código independiente de la tarea se escribe aqui

    // ahora esperamos el resultado
    int result = await tareaLarga;
    // tenemos el resultado y lo podemos utilizar en este punto
}

public async Task<int> SaveChangesAsync() // Retornamos un entero como ejemplo 
{
    await Task.Delay(1000); // 1 segundo de retardo
    return 1;
}

Now we explain:

TaskLoadLarge = SaveChangesAsync () runs independently on a separate thread. The code executed from this line is still running normally on the main thread and can take as long as you need. Then in the line int result = await taskLarge; The main thread waits for the thread created with SaveChangesAsync to follow the execution normally. In the case that the independent code of the main task takes more than 1 second, the SaveChangesAsync method will return 1 directly since the code has been executed in a separate thread maintaining the state.

    
answered by 09.10.2018 / 17:01
source