Skip to content

Instantly share code, notes, and snippets.

@Rickedb
Created March 23, 2022 00:40
Show Gist options
  • Save Rickedb/6cdc1f71313f587df4498576a5b45f78 to your computer and use it in GitHub Desktop.
Save Rickedb/6cdc1f71313f587df4498576a5b45f78 to your computer and use it in GitHub Desktop.
Useful extensions examples
public static class TaskExtensions
{
public static Task Ignore<TException>(this Task task) where TException : Exception
{
return task.ContinueWith(x =>
{
if (x.IsCanceled || !x.IsFaulted)
{
return Task.CompletedTask;
}
if (x.Exception != null && x.Exception.InnerException is TException)
{
return Task.CompletedTask;
}
throw x.Exception.InnerException;
}, TaskContinuationOptions.AttachedToParent);
}
public static Task<TResult> Ignore<TResult, TException>(this Task<TResult> task, TResult defaultValue = default(TResult)) where TException : Exception
{
return task.ContinueWith(x =>
{
if (x.IsCanceled || !x.IsFaulted)
{
return defaultValue;
}
if (x.Exception != null && x.Exception.InnerException is TException)
{
return defaultValue;
}
throw x.Exception.InnerException;
}, TaskContinuationOptions.AttachedToParent);
}
public static Task On<TException>(this Task task, Func<TException, Task> onException) where TException : Exception
{
return task.ContinueWith(x =>
{
if (x.IsCanceled || !x.IsFaulted)
{
return Task.CompletedTask;
}
if (x.Exception != null && x.Exception.InnerException is TException ex)
{
return onException(ex);
}
throw x.Exception.InnerException;
}, TaskContinuationOptions.AttachedToParent).Unwrap();
}
}
public static class TaskFactoryExtensions
{
public static Task StartNewNeverEndingTask(this TaskFactory factory, Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions = TaskCreationOptions.LongRunning, int delayMilisseconds = 1000)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
if (cancellationToken == default)
throw new ArgumentNullException(nameof(cancellationToken));
return factory.StartNew(async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
action();
await Task.Delay(delayMilisseconds, cancellationToken);
}
}, cancellationToken, creationOptions, TaskScheduler.Default);
}
public static Task StartNewNeverEndingTask(this TaskFactory factory, Func<Task> func, CancellationToken cancellationToken, TaskCreationOptions creationOptions = TaskCreationOptions.LongRunning, int delayMilisseconds = 1000)
{
if (func == null)
throw new ArgumentNullException(nameof(func));
if (cancellationToken == default)
throw new ArgumentNullException(nameof(cancellationToken));
return factory.StartNew(async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
await func();
await Task.Delay(delayMilisseconds, cancellationToken);
}
}, cancellationToken, creationOptions, TaskScheduler.Default);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment