Skip to content

Instantly share code, notes, and snippets.

@NDiiong
Created July 19, 2020 09:07
Show Gist options
  • Save NDiiong/add261cc6bda2c4033bdf39a60fdd891 to your computer and use it in GitHub Desktop.
Save NDiiong/add261cc6bda2c4033bdf39a60fdd891 to your computer and use it in GitHub Desktop.
public static class WatchHelper
{
public static void Track(Action action, ILogger logger, string message, string logFile)
{
message = message.PadRight(100, '.');
var sw = Stopwatch.StartNew();
try
{
action?.Invoke();
}
finally
{
sw.Stop();
logger.Write(message + $" - in {sw.ElapsedMilliseconds} ms", logger: logFile);
}
}
public static T Track<T>(Func<T> func, ILogger logger, string message, string logFile)
{
message = message.PadRight(100, '.');
var sw = Stopwatch.StartNew();
try
{
return func.Invoke() ?? default;
}
finally
{
sw.Stop();
logger.Write(message + $" - in {sw.ElapsedMilliseconds} ms", logger: logFile);
}
}
public static async Task TrackAsync(Func<Task> action, ILogger logger, string message, string logFile)
{
message = message.PadRight(100, '.');
var sw = Stopwatch.StartNew();
try
{
await action.Invoke().ConfigureAwait(false);
}
finally
{
sw.Stop();
logger.Write(message + $" - in {sw.ElapsedMilliseconds} ms", logger: logFile);
}
}
public static async Task<T> TrackAsync<T>(Func<Task<T>> func, ILogger logger, string message, string logFile)
{
message = message.PadRight(100, '.');
var sw = Stopwatch.StartNew();
try
{
return await func.Invoke().ConfigureAwait(false);
}
finally
{
sw.Stop();
logger.Write(message + $" - in {sw.ElapsedMilliseconds} ms", logger: logFile);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment