简体   繁体   中英

When to use Async methods in EF Core?

I'm building an application with an SQL database, with the following CRUD operations:

public Foo Add(Foo foo)
{
    _dbContext.Foos.Add(foo);
    _dbContext.SaveChanges();
    return foo;
}

public Foo Delete(int id)
{
    Foo foo = _dbContext.Foos.Find(id);
    if(foo != null)
    {
        _dbContext.Foos.Remove(foo);
        _dbContext.SaveChanges();
    }
    return foo;
}

However, some of these methods have asynchronous versions. The following still works:

public async Task<Foo> Add(Foo foo)
{
    await _dbContext.Foos.AddAsync(foo);
    await _dbContext.SaveChangesAsync();
    return foo;
}

public async Task<Foo> Delete(int id)
{
    Foo foo = await _dbContext.Foos.FindAsync(id);
    if(foo != null)
    {
        _dbContext.Foos.Remove(foo);
        await _dbContext.SaveChangesAsync();
    }
    return foo;
}

Is it only necessary when you still need the variable after calling the method?

As in Foo foo = await _dbContext.Foos.FindAsync(id);

What if I'm passing in a list of Foos to add to the database?

The rule of thumb is to use async on any thread that by it's busy type waiting, would hamper other threads. For the use of async will have the operations of waiting to step it aside until the data return.

Hence if you have a web service which handles multiple calls, usage of the async/await is good to implement to keep the web service responsive.

Is it only necessary when you still need the variable after calling the method?

Generally speaking, if there are asynchronous APIs, then you should use them for new code.

Asynchronous code frees up the calling thread. If your application is a GUI application, this can free up the UI thread; if your application is a server application, this can free up threads to handle other requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM