Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace AsyncTests.Infrastructure.Commands
- {
- #region using
- using System;
- using System.Threading.Tasks;
- using log4net;
- #endregion
- /// <summary>
- /// Async command execution.
- /// </summary>
- public static class AsyncCommandExecutor<T>
- {
- // NOTE: don't care about sharing this between instances.
- // ReSharper disable StaticFieldInGenericType
- private static readonly ILog Log = LogManager.GetLogger(typeof(AsyncCommandExecutor<>));
- // ReSharper restore StaticFieldInGenericType
- /// <summary>
- /// Executes the supplied command asynchronously.
- /// </summary>
- /// <param name="command">The command to execute.</param>
- public static async Task<T> Execute(IAsyncCommand<T> command, Action success = null, Action error = null)
- {
- var task = Task.Factory.StartNew(
- () =>
- {
- return command.Execute();
- });
- task.ContinueWith(
- t =>
- Log.Error(string.Format("'{0}' failed, something terrible happened.", command.GetType()), t.Exception),
- TaskContinuationOptions.OnlyOnFaulted);
- T result = await task;
- if (success != null && command.Successful)
- {
- success();
- }
- if (error != null && !command.Successful)
- {
- error();
- }
- return result;
- }
- }
- }
Add Comment
Please, Sign In to add comment