Example #1
0
        public static void ExecuteContinueWithInternal(this Task task,Action successAction,Action exceptionAction,
            Action cancellationAction)
        {
            task.ContinueWith(p => successAction(),
                TaskContinuationOptions.OnlyOnRanToCompletion);

            task.ContinueWith(p => exceptionAction(), TaskContinuationOptions.NotOnFaulted);

            task.ContinueWith(p => cancellationAction(),
                              TaskContinuationOptions.OnlyOnCanceled);
        }
        /// <summary>
        /// A helper method for mocking APM (classic) asynchronous methods with on TAP (modern) asynchronous methods.
        /// </summary>
        /// <remarks>
        /// This is based on <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx"/> 
        /// and <a href="http://msdn.microsoft.com/en-us/library/hh873178.aspx"/>.
        /// </remarks>
        public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state)
        {
            Debug.Assert(task != null, "task");

            var taskCompletionSource = new TaskCompletionSource<object>(state);
            task.ContinueWith(
                t =>
                {
                    if (t.IsFaulted)
                    {
                        taskCompletionSource.TrySetException(t.Exception.InnerExceptions);
                    }
                    else if (t.IsCanceled)
                    {
                        taskCompletionSource.TrySetCanceled();
                    }
                    else
                    {
                        taskCompletionSource.SetResult(null);
                    }

                    if (callback != null)
                    {
                         callback(taskCompletionSource.Task);
                    }
                },
                TaskScheduler.Default);

            return taskCompletionSource.Task;
        }
Example #3
0
		internal static Task ToApm(this Task task, AsyncCallback callback, object state) {
			if (task == null) {
				throw new ArgumentNullException("task");
			}

			var tcs = new TaskCompletionSource<object>(state);
			task.ContinueWith(
				t => {
					if (t.IsFaulted) {
						tcs.TrySetException(t.Exception.InnerExceptions);
					} else if (t.IsCanceled) {
						tcs.TrySetCanceled();
					} else {
						tcs.TrySetResult(null);
					}

					if (callback != null) {
						callback(tcs.Task);
					}
				},
				CancellationToken.None,
				TaskContinuationOptions.None,
				TaskScheduler.Default);

			return tcs.Task;
		}
 // The unobserved task handler extention. simply  observes the exception and do nothing.
 public static Task IgnoreExceptions(this Task task)
 {
     task.ContinueWith(c => { var ignored = c.Exception; },
         TaskContinuationOptions.OnlyOnFaulted |
         TaskContinuationOptions.ExecuteSynchronously);
     return task;
 }
Example #5
0
		/// <summary>
		/// A Task extension method that converts this object to an IAsyncResult.
		/// </summary>
		/// <remarks>
		/// Mark, 19/06/2012.
		/// Props to Stephen Toub for this blog post:
		/// http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx
		/// </remarks>
		/// <param name="task"> The task to act on.</param>
		/// <param name="callback">The callback.</param>
		/// <param name="state">The state.</param>
		/// <returns>
		/// The given data converted to an IAsyncResult-y Task.
		/// </returns>
		public static Task ToApm(this Task task, AsyncCallback callback, object state)
		{
			task = task ?? MakeCompletedTask();
			var tcs = new TaskCompletionSource<object>();
			task.ContinueWith(t =>
			{
				if (t.IsFaulted)
				{
					tcs.TrySetException(t.Exception.InnerExceptions);
				}
				else if (t.IsCanceled)
				{
					tcs.TrySetCanceled();
				}
				else
				{
					tcs.TrySetResult(null);
				}

				if (callback != null)
				{
					callback(tcs.Task);
				}
			}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
			return tcs.Task;
		}
Example #6
0
 public static void Forget(this Task task)
 {
     task.ContinueWith(t =>
     {
         var e = t.Exception;
     });
 }
Example #7
0
 public static void Forget(this Task task)
 {
     task.ContinueWith(t =>
     {
         Debugger.Break();
     }, TaskContinuationOptions.OnlyOnFaulted);
 }
 public static void LogOnException(this Task task)
 {
     task.ContinueWith(t =>
         {
             Log.Error("Exception thrown in task started with LogOnException()", t.Exception);
         },
         TaskContinuationOptions.OnlyOnFaulted);
 }
        public static void Ignore(this Task task)
        {
            Contract.Requires(task != null);

            // ReSharper disable CSharpWarnings::CS4014
            task.ContinueWith(t => t.Exception, TaskContinuationOptions.OnlyOnFaulted);
            // ReSharper restore CSharpWarnings::CS4014
        }
Example #10
0
 public static Task Catch(this Task task)
 {
     return task.ContinueWith(t =>
     {
         if (t.Exception != null)
             t.Exception.Handle(OnException);
     }, TaskContinuationOptions.OnlyOnFaulted);
 }
Example #11
0
 /// <summary>
 /// Observes any exceptions thrown by a task and performs an Action on them. (ie: logging). This does not occur on task cancellation. Recommended that you iterate over AggregateException.InnerExceptions in this.
 /// </summary>
 /// <param name="task"></param>
 /// <param name="action"></param>
 /// <returns></returns>
 public static Task OnExceptions(this Task task, Action<AggregateException> action)
 {
     task.ContinueWith(t =>
     {
         action(t.Exception.Flatten());
     }, TaskContinuationOptions.OnlyOnFaulted);
     return task;
 }
 public static void WaitWithPumping(this Task task)
 {
     if (task == null) throw new ArgumentNullException("task");
     var nestedFrame = new DispatcherFrame();
     task.ContinueWith(_ => nestedFrame.Continue = false);
     Dispatcher.PushFrame(nestedFrame);
     task.Wait();
 }
Example #13
0
        public static void Wait(this Task t)
        {
            var e = new System.Threading.ManualResetEvent(false);

            t.ContinueWith(_ => e.Set());

            e.WaitOne();
        }
Example #14
0
 public static Task FailFastOnException(this Task task)
 {
     task.ContinueWith(c =>
         Environment.FailFast(
             "An unhandled exception occurred in a background task",  c.Exception),
         TaskContinuationOptions.OnlyOnFaulted |  TaskContinuationOptions.ExecuteSynchronously);
     return task;
 }
Example #15
0
 public static void FireAndForget(this Task task,string taskName,Action<Task> errorHandler=null)
 {
     if (errorHandler == null)
     {
         errorHandler = t => taskName.LogError(t.Exception);
     }
     task.ContinueWith(errorHandler, TaskContinuationOptions.OnlyOnFaulted);
 }
        public static Task ChainFailureHandler(this Task task, string message)
        {
            // create a handler that will raise an exception if an operation fails...
            return task.ContinueWith((t) =>
            {


            }, TaskContinuationOptions.OnlyOnFaulted);
        }
Example #17
0
 public static Task IgnoreExceptions(this Task task)
 {
     task.ContinueWith(
         t => { var ignored = t.Exception; },
         CancellationToken.None,
         TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted,
         TaskScheduler.Default);
     return task;
 }
 /// <summary>
 /// Logs the and then ignores the exceptions thrown from the task if any.
 /// </summary>
 /// <param name="self">The task itself</param>
 /// <param name="logger">Logger to log against</param>
 /// <param name="msg">Optional message to be included</param>
 /// <param name="logLevel">Optional parameter to set log level</param>
 public static void LogAndIgnoreExceptionIfAny(this Task self, Logger logger, string msg = "", Level logLevel = Level.Error)
 {
     self.ContinueWith(t =>
     {
         // ReSharper disable once PossibleNullReferenceException ; We know the task is Faulted
         logger.Log(logLevel, "{0} Exception:{1}", t.Exception.GetBaseException());
     },
         TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
 }
 public static void LogAggregateExceptions(this Task task)
 {
     task.ContinueWith(t =>
     {
         var aggregateException = t.Exception.Flatten();
         foreach (var ex in aggregateException.InnerExceptions) Trace.TraceError(ex.ToString());
     },
         TaskContinuationOptions.OnlyOnFaulted);
 }
 public static Task<IEnumerable<User>> FromEntitiesAsync(this Task<List<UserEntity>> userEntities)
 {
     return userEntities.ContinueWith(task =>
     {
         task.ThrowIfFaulted();
         var entities = task.Result;
         return entities.FromEntity();
     }, TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously);
 }
Example #21
0
 public static void LogExceptions(this Task task, Action<Exception> logException)
 {
     task.ContinueWith(t =>
     {
         var aggException = t.Exception.Flatten();
         foreach (var exception in aggException.InnerExceptions)
             logException(exception);
     },
     TaskContinuationOptions.OnlyOnFaulted);
 }
Example #22
0
 public static Task ContinueFaultWith(this Task task, Action<Task> continuationAction)
 {
     return task.ContinueWith(_ =>
     {
         if(_.IsFaulted)
         {
             continuationAction(_);
         }
     });
 }
 public static void LogOnFaulure(this Task task)
 {
     task.ContinueWith(
         t =>
         {
             // todo: log
             Console.WriteLine(t.Exception);
         },
         TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
 }
Example #24
0
 public static void LogExceptions(this Task task)
 {
     task.ContinueWith(t =>
     {
         var aggException = t.Exception.Flatten();
         foreach (var exception in aggException.InnerExceptions)
             Logger.WriteLog(exception, "Task异常");
     },
     TaskContinuationOptions.OnlyOnFaulted);
 }
Example #25
0
        // adapted from http://blogs.planetsoftware.com.au/paul/archive/2010/12/05/waiting-for-a-task-donrsquot-block-the-main-ui-thread.aspx
        public static void WaitWithPumping(this Task task)
        {
            if (task == null)
                return;

            var nestedFrame = new DispatcherFrame();
            task.ContinueWith(_ => nestedFrame.Continue = false);
            Dispatcher.PushFrame(nestedFrame);
            task.Wait();
        }
        public static Task<User> FromEntityAsync(this Task<UserEntity> userTask)
        {
            return userTask.ContinueWith(task =>
            {
                task.ThrowIfFaulted();
                var entity = task.Result;
                return FromEntity(entity);

            }, TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously);
        }
 /// <summary>
 /// Rethrows exceptions thrown during task execution in thespecified dispatcher thread.
 /// </summary>
 /// <param name="task">The task.</param>
 /// <param name="dispatcher">The dispatcher.</param>
 /// <returns></returns>
 public static Task WithExceptionThrowingInDispatcher(this Task task, Dispatcher dispatcher)
 {
     return task.ContinueWith(t =>
     {
         dispatcher.BeginInvoke(() =>
         {
             throw t.Exception;
         }, DispatcherPriority.Send);
     }, TaskContinuationOptions.OnlyOnFaulted);
 }
Example #28
0
 public static Task HandleExceptions(this Task task, Action<Exception> onException = null)
 {
     return task.ContinueWith(t =>
     {
         var exception = t.Exception.Flatten();
         onException = onException ?? (exc => Trace.WriteLine(exc, "Task.HandleExceptions"));
         foreach (var ex in exception.InnerExceptions)
             onException(ex);
     },
     TaskContinuationOptions.OnlyOnFaulted);
 }
Example #29
0
 public static void HandleExceptions(this Task task, Action<Exception> Handler)
 {
     task.ContinueWith(t => {
         if (t != null && t.Exception != null) {
             AggregateException aggException = t.Exception.Flatten();
             foreach (Exception exception in aggException.InnerExceptions) {
                 Handler(exception);
             }
         }
     }, TaskContinuationOptions.OnlyOnFaulted);
 }
 public static void FireAndForget(this Task task)
 {
     task.ContinueWith(t =>
     {
         if (t.IsFaulted)
         {
             var aggException = t.Exception.Flatten();
             foreach(var exception in aggException.InnerExceptions)
                 System.Diagnostics.Debug.WriteLine("Fire and Forget failed: " + exception.Message + " - " + exception.StackTrace);
         }
     });
 }