The most common programming practice is to catch exceptions and log them. Logging involves IO since we usually log into files or database. IO operations are usually expensive in terms of performance which means that in a serviced kind of environment, the end user who is waiting for a response is actually being kept waiting for logging messages as well.
Logging and Auditing are cross cutting concerns, which means that they are not specific to a particular layer in application architecture but used throughout. To make performant systems we should write code in a way which returns response to user as soon as possible. In past to improve performance we used to write in in-memory buffers and later dump that buffer into files or database. This reduces the IO but poses challenges like if program crashed we might lost onto important information which could have helped in troubleshooting.
C# 5 brings Async and Await keywords to the table. Async and Await are code markers which frees the thread if it’s waiting for some IO operation. This improves performance in web application where threads are utilized from ThreadPool. Since as soon as compiler encounters an await keyword, it marks the rest of method as continuation or callback and return the caller thread to pool. Once free this thread can cater to other requests and when IO operation completes, the marked callback is executed by a free thread from ThreadPool.
In C# 6.0 we can write the logging and auditing code using async and await
public async void ExceptionFilters()
{
try
{
//Do Something
}
catch (Exception ex) if (!ex.GetType().Equals(typeof(ArithmeticException)))
{
await Task.Run(() => {
var writer = new StreamWriter("c:\\temp\\logtester.log", true);
writer.Write("Some value to log");
});
//More code
}
}