mirror of https://github.com/ogoun/Zero.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
1.1 KiB
38 lines
1.1 KiB
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace ZeroLevel.Services.Async
|
|
{
|
|
public static class AsyncHelper
|
|
{
|
|
private static readonly TaskFactory _taskFactory = new
|
|
TaskFactory(CancellationToken.None,
|
|
TaskCreationOptions.None,
|
|
TaskContinuationOptions.None,
|
|
TaskScheduler.Default);
|
|
|
|
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
|
|
=> _taskFactory
|
|
.StartNew(func)
|
|
.Unwrap()
|
|
.GetAwaiter()
|
|
.GetResult();
|
|
|
|
public static void RunSync(Func<Task> func)
|
|
=> _taskFactory
|
|
.StartNew(func)
|
|
.Unwrap()
|
|
.GetAwaiter()
|
|
.GetResult();
|
|
|
|
public async static Task<T> WithTimeout<T>(this Task<T> task, int duration)
|
|
{
|
|
var retTask = await Task.WhenAny(task, Task.Delay(duration))
|
|
.ConfigureAwait(false);
|
|
|
|
if (retTask is Task<T>) return task.Result;
|
|
return default(T);
|
|
}
|
|
}
|
|
} |