A few steps that need to be done to create an asynchronous method from its counterpart synchronous method:
1. make sure System.Threading.Tasks is referred in one of the using statements
2. change the method return type to be async Task<returntype> or simply async Task if the original method was decorated with void
3. call the asynchronous version of the Entity Framework method
4. most of the time, use await keyword just before the Entity Framework asynchronous method. We could assign the result to a Task variable first then call the await keyword a little bit later if we have some operation that can be executed right away and is not dependent on the asynchronous method's result.
Below are a few simple examples:
- an example of a method that does not return anything
// original synchronous method public void Insert(Person person) { _context.Person.Add(person); _context.SaveChanges(); } // the async version public async Task InsertAsync(Person person) { _context.Person.Add(person); await _context.SaveChangesAsync(); }
- an example of a method returning a value
// original synchronous method public int GetTotal() { return _context.Person.Count(); } // the async version public async Task<int> GetTotalAsync() { return await _context.Person.CountAsync(); }
- an example that shows using await a little bit later:
// original synchronous method public int GetTotalNumber() { var result = _context.Person.Count(); DoSomeOtherOperation(); return result; } // the async version public async Task<int> GetTotalNumberAsync() { var result = _context.Person.CountAsync(); // use await a little bit later // do non-related operation to the result above DoSomeOtherOperation(); return await result; }
On the next post we will see these concepts in more details.
2 comments:
Good morning from Germany,
nice post! Just a detail, but public void int MethodName() won't compile, I think.
Cheers!
Yes, of course.. Thank you for pointing this out. I have fixed those.
Post a Comment