Implementing the async version of the synchronization method: how to return Task <int>, which is constant 1?

I have a synchronization method, now I would like to implement my asynchronous version. Fortunately, the base call already has an asynchronous version ( dbSet.SaveChangesAsync()), however in my algorithm there is an if branch returning with a constant literal 1.

I do not know how to implement this part in the asynchronous version?

Sync Version:

    public virtual int Add(T entity)
    {
        SetLogContext(entity, _logctx);
        dbSet.Add(entity);

        if (isAutonomous)
        {
            return ctx.SaveChanges();
        }
        return 1;
    }

Asynchronous version:

    public virtual Task<int> AddAsync(T entity)
    {
        SetLogContext(entity, _logctx);
        dbSet.Add(entity);

        if (isAutonomous)
        {
            return ctx.SaveChangesAsync();
        }
        return ??? // What to write here?
    }
+4
source share
3 answers

Using

return Task.FromResult(1);
+8
source

You have two options to achieve your needs: you need to use the keyword async:

public virtual async Task<int> AddAsync<T>(T entity)
{
    SetLogContext(entity, _logctx);
    dbSet.Add(entity);

    if (isAutonomous)
    {
        return await ctx.SaveChangesAsync();
    }
    return 1;
}

Another is to use Task.FromResult(1)at the point where you want to return the number.

+3

, , , "Async", async. , .

@xxMUROxx, "Async" async.

    public virtual async Task<int> AddAsync<T>(T entity)
    {
        SetLogContext(entity, _logctx);
        dbSet.Add(entity);

        if (isAutonomous)
        {
            return await ctx.SaveChangesAsync();
        }
        return 1;
    }

async await - . await , . async void, .

When this happens, it allows the caller to continue working while it waits for the completion of a long operation. After completing a lengthy operation, the code will create a continuation and continue to execute any other code that depends on the returned result.

Omitting the keyword asyncfrom the method, you again made a synchronous call. Overcoming the goal of the challenge SaveChangesAsyncin the first place.

0
source

Source: https://habr.com/ru/post/1589139/


All Articles