62 lines
2.7 KiB
C#
62 lines
2.7 KiB
C#
using mbts;
|
|
|
|
namespace System.Threading.Tasks {
|
|
public static class NonGenericTaskExtensions {
|
|
public static Task ContinueOnDispatcher(this Task task, Action<Task> continuationAction) {
|
|
return task.ContinueWith(continuationAction, TaskScheduler.FromCurrentSynchronizationContext());
|
|
}
|
|
|
|
public static Task<TResult> SelectOnDispatcher<TResult>(this Task task, Func<Task, TResult> selector) =>
|
|
task.ContinueWith(selector, TaskScheduler.FromCurrentSynchronizationContext());
|
|
|
|
public static Task<TResult> SelectOnDispatcherAsync<TResult>(this Task task, Func<Task, Task<TResult>> selector_async) =>
|
|
task.ContinueWith(selector_async, TaskScheduler.FromCurrentSynchronizationContext()).Unwrap();
|
|
}
|
|
|
|
public static class GenericTaskExtensions {
|
|
public static Task ContinueOnDispatcher<T>(this Task<T> task, Action<Task<T>> continuationAction) {
|
|
return task.ContinueWith(continuationAction, TaskScheduler.FromCurrentSynchronizationContext());
|
|
}
|
|
|
|
public static Task ContinueOnDispatcher<T>(this Task<T> task, Action<Task<T>> continuationAction, TaskContinuationOptions continuationOptions) {
|
|
return task.ContinueWith(continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.FromCurrentSynchronizationContext());
|
|
}
|
|
|
|
public static Task<TResult> ContinueOnDispatcher<T, TResult>(this Task<T> task, Func<Task<T>, TResult> continuationFunc) {
|
|
return task.ContinueWith(continuationFunc, TaskScheduler.FromCurrentSynchronizationContext());
|
|
}
|
|
}
|
|
|
|
public static class TaskHelper {
|
|
public static async void DelayAction(TimeSpan delay, Action action, CancellationTokenSource cts) {
|
|
await Task.Delay(delay);
|
|
if (cts == null || !cts.IsCancellationRequested) action();
|
|
}
|
|
|
|
public static async void DelayAction(TimeSpan delay, Action action, Func<bool> get_is_canceled) {
|
|
await Task.Delay(delay);
|
|
if (!get_is_canceled()) action();
|
|
}
|
|
|
|
public static IDisposable DelayAction(TimeSpan delay, Action action) {
|
|
var cts = new CancellationTokenSource();
|
|
Task.Run(async () => {
|
|
await Task.Delay(delay);
|
|
if (!cts.IsCancellationRequested) action();
|
|
});
|
|
return Disposable.Create((Action)cts.Cancel);
|
|
}
|
|
|
|
public static IDisposable DelayActionThreadSafe(TimeSpan delay, Action action) {
|
|
var cts = new CancellationTokenSource();
|
|
run();
|
|
return Disposable.Create((Action)cts.Cancel);
|
|
|
|
async void run() {
|
|
await Task.Delay(delay);
|
|
if (!cts.IsCancellationRequested)
|
|
action();
|
|
}
|
|
}
|
|
}
|
|
} |