Database Reference
In-Depth Information
private static async Task ShowAccountTransactionsAsync(int accountNumber)
{
Console.WriteLine("TxNumber\tDate\tAmount");
using (var context = new EF6RecipesContext())
{
var transactions = context.Transactions.Where(t => t.AccountNumber == accountNumber);
await transactions.ForEachAsync(t => Console.WriteLine("{0}\t{1}\t{2}",
t.TransactionNumber, t.TransactionDate, t.Amount));
}
}
How It Works
Asynchronous constructs were introduced in .NET 4.5 to reduce the complexity normally associated with
writing asynchronous code. When we call SaveAccountTransactionsAsync() , we assign it to a Task object,
which calls the method and then returns execution control to the caller while the asynchronous portion of the
SaveAccountTransactionsAsync() method is executing. The code that calls ShowAccountTransactionsAsync()
is structured in much the same way. When the awaited calls in each of these two methods return, execution returns
to the line following the caller's await statement.
It's important to know that the async model in .NET 4.5 is single-threaded rather than multi-threaded, so the
code that follows await SaveAccountTransactionsAsync() is suspended until SaveAccountTransactionsAsync()
returns. It's additionally important to know that any method that calls an async method must itself be marked with
the async modifier and have Task or Task<T> as its return type.
The output of the code in Listing 7-10 is shown below.
Account Transactions for the account belonging to Robert Dewey (acct# 1)
TxNumber Date Amount
1 7/5/2013 12:00:00 AM 104.00
2 7/12/2013 12:00:00 AM 104.00
3 7/19/2013 12:00:00 AM 104.00
7 8/9/2013 12:00:00 AM -5.00
8 8/9/2013 12:00:00 AM -2.00
Account Transactions for the account belonging to James Cheatham (acct# 2)
TxNumber Date Amount
4 8/1/2013 12:00:00 AM 900.00
5 8/2/2013 12:00:00 AM -42.00
9 8/9/2013 12:00:00 AM -5.00
10 8/9/2013 12:00:00 AM -2.00
Account Transactions for the account belonging to Thurston Howe (acct# 3)
TxNumber Date Amount
6 8/5/2013 12:00:00 AM 100.00
11 8/9/2013 12:00:00 AM -5.00
12 8/9/2013 12:00:00 AM -2.00
 
Search WWH ::




Custom Search