75 lines
3.0 KiB
C#
75 lines
3.0 KiB
C#
namespace AyCode.Core.Helpers
|
|
{
|
|
public static class TaskHelper
|
|
{
|
|
public static bool WaitTo(Func<bool> predicate, int msTimeout = 10000, int msDelay = 5, int msFirstDelay = 0)
|
|
=> WaitToAsync(predicate, msTimeout, msDelay, msFirstDelay).GetAwaiter().GetResult();
|
|
|
|
public static Task<bool> WaitToAsync(Func<bool> predicate, int msTimeout = 10000, int msDelay = 5, int msFirstDelay = 0)
|
|
{
|
|
return ToThreadPoolTask(async () =>
|
|
{
|
|
var result = false;
|
|
var dtTimeout = DateTime.UtcNow.AddMilliseconds(msTimeout).Ticks;
|
|
|
|
if (msFirstDelay > 0) await Task.Delay(msFirstDelay).ConfigureAwait(false);
|
|
|
|
while (dtTimeout > DateTime.UtcNow.Ticks && !(result = predicate()))
|
|
await Task.Delay(msDelay).ConfigureAwait(false); //Thread.Sleep(msDelay);
|
|
|
|
return result;
|
|
});
|
|
}
|
|
|
|
public static void Forget(this Task task)
|
|
{
|
|
if (!task.IsCompleted || task.IsFaulted)
|
|
_ = ForgetAwaited(task);
|
|
|
|
static async Task ForgetAwaited(Task task)
|
|
{
|
|
try
|
|
{
|
|
await task.ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await Task.FromException(ex).ConfigureAwait(true);
|
|
}
|
|
}
|
|
}
|
|
|
|
//public static void Forget(this ValueTask task)
|
|
//{
|
|
// if (!task.IsCompleted || task.IsFaulted)
|
|
// _ = ForgetAwaited(task);
|
|
|
|
// static async ValueTask ForgetAwaited(ValueTask task)
|
|
// {
|
|
// try
|
|
// {
|
|
// await task.ConfigureAwait(false);
|
|
// }
|
|
// catch (Exception ex)
|
|
// {
|
|
// //TODO: .net5, .net6 feature! - J.
|
|
// ValueTask.FromException(ex).ConfigureAwait(true);
|
|
// }
|
|
// }
|
|
//}
|
|
|
|
//TODO: Cancellation token params - J.
|
|
//public static void RunOnThreadPool(this Task task) => Task.Run(() => _ = task).Forget(); //TODO: Letesztelni, a ThreadId-kat! - J.
|
|
public static void RunOnThreadPool(this Action action) => ToThreadPoolTask(action).Forget();
|
|
public static void RunOnThreadPool<T>(this Func<T> func) => ToThreadPoolTask(func).Forget();
|
|
|
|
public static Task ToThreadPoolTask(this Action action) => Task.Run(action);
|
|
|
|
//public static Task ToThreadPoolTask(this Task task) => Task.Run(() => _ = task);
|
|
//public static void ToParallelTaskStart(this Task task) => task.Start();
|
|
//public static Task<T> ToThreadPoolTask<T>(this Task<T> task) => Task.Run(() => task);
|
|
public static Task<T> ToThreadPoolTask<T>(this Func<Task<T>> func) => Task.Run(func); //TODO: Letesztelni, a ThreadId-kat! - J.
|
|
public static Task<T> ToThreadPoolTask<T>(this Func<T> func) => Task.Run(func);
|
|
}
|
|
}
|