The following code combines a reporter interface and an Action<IReport> to demonstrate how paramters are passed around
using System;
using System.Threading;
namespace MyApplication
{
public class Program
{
static void Main()
{
var measurer = new Measurer();
measurer.Measure((reporter) =>
{
reporter.WriteLine("Starting work ...");
Work(1000, reporter);
}, true);
}
static void Work(int duration, IReport reporter)
{
reporter.WriteLine("Going to sleep ...");
Thread.Sleep(duration);
reporter.WriteLine("Waking up ...");
throw new TimeoutException();
}
}
public interface IReport
{
void WriteLine(string text, params object[] arguments);
}
public class ConsoleReporter : IReport
{
public void WriteLine(string text, params object[] arguments)
{
Console.WriteLine(text, arguments);
}
}
public class Measurer
{
public void Measure(Action<IReport> action, bool trapException)
{
var start = DateTime.Now;
var reporter = new ConsoleReporter();
try { action(reporter); }
catch (Exception ex)
{
if (trapException)
reporter.WriteLine("Action failed with a {0}: {1}", ex.GetType().Name, ex.Message);
else
throw;
}
reporter.WriteLine("Action executed in {0:f2} seconds", (DateTime.Now - start).TotalSeconds);
}
}
}
/* Output: * Starting work ... * Going to sleep ... * Waking up ... * Action failed with a TimeoutException: The operation has timed out. * Action executed in 1,01 seconds */