Friday, June 29, 2018

C# Entity Framework : Asynchronous Programming (async/await)


Asynchronous programming is a means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure or progress. The main benefits one can gain from using asynchronous programming are improved application performance and responsiveness.

Entity Framework 6.0 supports asynchronous Programming, it means asynchronously you can query data and save data. By using async/await you can easily write the asynchronous programming for entity framework.

Example:

public async Task<Project> GetProjectAsync(string name)
{
 DBContext _localdb = new DBContext();
 return await _localdb.Projects.FirstOrDefaultAsync(x => x.Name == name);
}

In above example, asynchronously return the first element of records which satisfied condition or default value.

public async Task<Project> SaveProjectAsync(Project project)
{
 DBContext _localdb = new DBContext();
_localdb.Projects.Add(project);
 await _localdb.SaveChangesAsync();
 return project;
}

In above example, asynchronously saves all changes made in this context to the underlying database.

if you are doing asynchronous programming in entity framework, then the each async method should have own DBContext object otherwise if you are sharing dbcontext among multiple threads it could thrown exception


other links related to entity framework : 

Thanks for visiting!!

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...