Skip to content

Instantly share code, notes, and snippets.

@rizal-almashoor
Created May 28, 2012 08:53
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save rizal-almashoor/2818038 to your computer and use it in GitHub Desktop.
Save rizal-almashoor/2818038 to your computer and use it in GitHub Desktop.
Exception-handling wrappers for Task.ContinueWith()
Copyright (c) 2012 Rizal Almashoor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Net;
using System.Threading.Tasks;
namespace Examples
{
class Program
{
static void Main(string[] args)
{
var taskHelperExample = new TaskHelperExample();
taskHelperExample.Run("http://www.google.com");
Console.ReadLine();
}
}
class TaskHelperExample
{
public void Run(string url)
{
Task.Factory.StartNew(StartBusyIndicator)
.Then(task => GetWebResponseAsync(url))
.Then(task => Console.WriteLine(task.Result.Headers))
.Finally(ExceptionHandler, StopBusyIndicator);
}
private Task<WebResponse> GetWebResponseAsync(string url)
{
var webRequest = WebRequest.Create(url);
return Task.Factory.FromAsync<WebResponse>(webRequest.BeginGetResponse, webRequest.EndGetResponse, null);
}
private void StartBusyIndicator()
{
Console.WriteLine("Please wait ...");
}
private void StopBusyIndicator()
{
Console.WriteLine("Done.");
}
private void ExceptionHandler(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
// Copyright (c) 2012 Rizal Almashoor
// Licensed under the MIT license.
// http://gist.github.com/2818038#file_license.txt
using System.Linq;
namespace System.Threading.Tasks
{
public static class TaskHelper
{
// Inspired by http://blogs.msdn.com/b/pfxteam/archive/2010/11/21/10094564.aspx
public static Task Then(this Task task, Action<Task> next)
{
if (task == null) throw new ArgumentNullException("task");
if (next == null) throw new ArgumentNullException("next");
var tcs = new TaskCompletionSource<AsyncVoid>();
task.ContinueWith(previousTask =>
{
if (previousTask.IsFaulted) tcs.TrySetException(previousTask.Exception);
else if (previousTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
next(previousTask);
tcs.TrySetResult(default(AsyncVoid));
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
public static Task Then(this Task task, Func<Task, Task> next)
{
if (task == null) throw new ArgumentNullException("task");
if (next == null) throw new ArgumentNullException("next");
var tcs = new TaskCompletionSource<AsyncVoid>();
task.ContinueWith(previousTask =>
{
if (previousTask.IsFaulted) tcs.TrySetException(previousTask.Exception);
else if (previousTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
next(previousTask).ContinueWith(nextTask =>
{
if (nextTask.IsFaulted) tcs.TrySetException(nextTask.Exception);
else if (nextTask.IsCanceled) tcs.TrySetCanceled();
else tcs.TrySetResult(default(AsyncVoid));
});
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
public static Task<TNextResult> Then<TNextResult>(this Task task, Func<Task, TNextResult> next)
{
if (task == null) throw new ArgumentNullException("task");
if (next == null) throw new ArgumentNullException("next");
var tcs = new TaskCompletionSource<TNextResult>();
task.ContinueWith(previousTask =>
{
if (previousTask.IsFaulted) tcs.TrySetException(previousTask.Exception);
else if (previousTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
tcs.TrySetResult(next(previousTask));
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
public static Task<TNextResult> Then<TNextResult>(this Task task, Func<Task, Task<TNextResult>> next)
{
if (task == null) throw new ArgumentNullException("task");
if (next == null) throw new ArgumentNullException("next");
var tcs = new TaskCompletionSource<TNextResult>();
task.ContinueWith(previousTask =>
{
if (previousTask.IsFaulted) tcs.TrySetException(previousTask.Exception);
else if (previousTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
next(previousTask).ContinueWith(nextTask =>
{
if (nextTask.IsFaulted) tcs.TrySetException(nextTask.Exception);
else if (nextTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
tcs.TrySetResult(nextTask.Result);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
public static Task Then<TResult>(this Task<TResult> task, Action<Task<TResult>> next)
{
if (task == null) throw new ArgumentNullException("task");
if (next == null) throw new ArgumentNullException("next");
var tcs = new TaskCompletionSource<AsyncVoid>();
task.ContinueWith(previousTask =>
{
if (previousTask.IsFaulted) tcs.TrySetException(previousTask.Exception);
else if (previousTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
next(previousTask);
tcs.TrySetResult(default(AsyncVoid));
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
public static Task Then<TResult>(this Task<TResult> task, Func<Task<TResult>, Task> next)
{
if (task == null) throw new ArgumentNullException("task");
if (next == null) throw new ArgumentNullException("next");
var tcs = new TaskCompletionSource<AsyncVoid>();
task.ContinueWith(previousTask =>
{
if (previousTask.IsFaulted) tcs.TrySetException(previousTask.Exception);
else if (previousTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
next(previousTask).ContinueWith(nextTask =>
{
if (nextTask.IsFaulted) tcs.TrySetException(nextTask.Exception);
else if (nextTask.IsCanceled) tcs.TrySetCanceled();
else tcs.TrySetResult(default(AsyncVoid));
});
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
public static Task<TNextResult> Then<TResult, TNextResult>(this Task<TResult> task, Func<Task<TResult>, TNextResult> next)
{
if (task == null) throw new ArgumentNullException("task");
if (next == null) throw new ArgumentNullException("next");
var tcs = new TaskCompletionSource<TNextResult>();
task.ContinueWith(previousTask =>
{
if (previousTask.IsFaulted) tcs.TrySetException(previousTask.Exception);
else if (previousTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
tcs.TrySetResult(next(previousTask));
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
public static Task<TNextResult> Then<TResult, TNextResult>(this Task<TResult> task, Func<Task<TResult>, Task<TNextResult>> next)
{
if (task == null) throw new ArgumentNullException("task");
if (next == null) throw new ArgumentNullException("next");
var tcs = new TaskCompletionSource<TNextResult>();
task.ContinueWith(previousTask =>
{
if (previousTask.IsFaulted) tcs.TrySetException(previousTask.Exception);
else if (previousTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
next(previousTask).ContinueWith(nextTask =>
{
if (nextTask.IsFaulted) tcs.TrySetException(nextTask.Exception);
else if (nextTask.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
tcs.TrySetResult(nextTask.Result);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
/// <summary>
/// Analogous to the finally block in a try/finally
/// </summary>
public static void Finally(this Task task, Action<Exception> exceptionHandler, Action finalAction = null)
{
task.ContinueWith(t =>
{
if (finalAction != null) finalAction();
if (t.IsCanceled || !t.IsFaulted || exceptionHandler == null) return;
var innerException = t.Exception.Flatten().InnerExceptions.FirstOrDefault();
exceptionHandler(innerException ?? t.Exception);
});
}
}
public struct AsyncVoid
{
// Based on Brad Wilson's idea, to simulate a non-generic TaskCompletionSource
// http://bradwilson.typepad.com/blog/2012/04/tpl-and-servers-pt4.html
}
}
@StanislavChankov
Copy link

StanislavChankov commented May 8, 2018

Consider explicitly setting the TaskScheduler in ContinueWith to TaskScheduler.Default instead of letting the default TaskScheduler.Current which could result to problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment