DBContext SaveChangesAsync waits and does not continue

3

I have a webapi assembled with the repository pattern and work unit and I need to make an asynchronous save but I do not get it.

In my service layer I have the following:

List<Task> guardadosAsincronos = new List<Task>();
while (...) {
    ...
    guardadosAsincronos.Add(this.SaveAsync());
    ...
}
for (var i = 0; i < guardadosAsincronos.Count; i++) {
    guardadosAsincronos[i].Wait();
}

Each class in the service layer extends from another base that contains the following function:

public async Task<int> SaveAsync() {
    int result = await this._unitOfWork.CommitAsync();
    return result;
}

This calls the function of the UnitOfWork class:

public Task<int> CommitAsync() {
    return this._databaseFactory.Get().CommitAsync();
}

and in turn, this calls to the context:

public virtual Task<int> CommitAsync() {
    return base.SaveChangesAsync(new System.Threading.CancellationToken());
}

When I do the first save, the functions are called one after the other but, when the context function is reached, the execution stops, so instead of an asynchronous save, one becomes synchronous and my loop The main layer of the service layer does not continue until the save ends.

Can someone tell me what I'm doing wrong so that the asynchronous save is not done ???

    
asked by Alejandro 16.10.2017 в 10:15
source

1 answer

0

Eliminate the for where you execute the Wait() method. According to the documentation of the Wait () method :

  

Wait for the task to complete execution.

What clearly gives to understand, that until the execution of each thread is finished, the Wait will stop the execution and wait for the method to continue to finish.

For example:

 List<Task> ts = new List<Task>
{
    Task.Factory.StartNew(()=>{ Thread.Sleep(2000); Console.WriteLine("Ejecutando hilo 1"); }),
    Task.Factory.StartNew(()=>{ Thread.Sleep(2000); Console.WriteLine("Ejecutando hilo 2"); }),
    Task.Factory.StartNew(()=>{ Thread.Sleep(2000); Console.WriteLine("Ejecutando hilo 3"); })
};

foreach (var t in ts)
{
    t.Wait();
}
Console.WriteLine("Termino");

The result of the printing should be so to be asynchronous:

Termino
Ejecutando hilo 2
Ejecutando hilo 1
Ejecutando hilo 3

But in reality it is:

Ejecutando hilo 1
Ejecutando hilo 2
Ejecutando hilo 3
Termino

Which indicates that it is not running asynchronously at all since it is executed according to the order in which it was created, which it should not be (at least it should not be the rule). Whereas if we eliminate the execution of Wait() , the expected result is printed.

    
answered by 16.10.2017 в 15:39