background task helpers

Feb 18, 2011 at 11:56 PM

I just started switching from usage of System.ComponentModel.BackGroundWorker to System.Threading.Tasks, and I am really digging the composability. Below are some methods I have added to Execute. Between these and a nice ProgressReporter utility from http://nitoprograms.blogspot.com/2010/06/reporting-progress-from-tasks.html, there is nothing I miss about BackgroundWorker...

 

/// <summary>
/// Begins execution of a <see cref="Task"/> on a background thread.
/// </summary>
public static Task OnBGThread(System.Action backgroundAction, bool useDefaultExceptionHandler = true)
{
	var task = Task.Factory.StartNew(backgroundAction);
	if (useDefaultExceptionHandler)
		return task.WithExceptionHandler(t => _exceptionHandler.Handle(t.Exception));
	return task;
}

/// <summary>
/// Begins execution of a cancellable <see cref="Task"/> on a background thread.
/// </summary>
public static Task OnBGThreadCancellable(System.Action<CancellationToken> backgroundAction, CancellationToken token, bool useDefaultExceptionHandler = true)
{
	return OnBGThread(() => backgroundAction(token), useDefaultExceptionHandler);
}

/// <summary>
/// Begins execution of a <see cref="Task<T>"/> on a background thread.
/// </summary>
public static Task<T> OnBGThread<T>(System.Func<T> backgroundAction, bool useDefaultExceptionHandler = true)
{
	var task = Task<T>.Factory.StartNew(backgroundAction);
	if (useDefaultExceptionHandler)
		return task.WithExceptionHandler(t => _exceptionHandler.Handle(t.Exception));
	return task;
}

/// <summary>
/// Begins execution of a cancellable <see cref="Task<T>"/> on a background thread.
/// </summary>
public static Task<T> OnBGThreadCancellable<T>(System.Func<CancellationToken, T> backgroundAction, CancellationToken token, bool useDefaultExceptionHandler = true)
{
	return OnBGThread<T>(() => backgroundAction(token), useDefaultExceptionHandler);
}

 

 

 

public static class TaskExtensionMethods
{
	/// <summary>
	/// Adds an exception handler continuation to the given task
	/// </summary>
	public static Task WithExceptionHandler(
		this Task source, Action<Task> handler)
	{
		source.ContinueWith(t => handler(t), TaskContinuationOptions.OnlyOnFaulted);
		return source;
	}

	/// <summary>
	/// Adds an exception handler continuation to the given task
	/// </summary>
	public static Task<T> WithExceptionHandler<T>(
		this Task<T> source, Action<Task<T>> handler)
	{
		source.ContinueWith(t => handler(t), TaskContinuationOptions.OnlyOnFaulted);
		return source;
	}
}