using System;
using System.Threading;
using System.Threading.Tasks;
namespace MinecraftClient
{
///
/// Allow easy timeout on pieces of code
///
///
/// By ORelio - (c) 2014 - CDDL 1.0
///
public class AutoTimeout
{
///
/// Perform the specified action with specified timeout
///
/// Action to run
/// Maximum timeout in milliseconds
/// True if the action finished whithout timing out
public static bool Perform(Action action, int timeout)
{
return Perform(action, TimeSpan.FromMilliseconds(timeout));
}
public static Task PerformAsync(Action action, int timeout, CancellationToken cancellationToken = default)
{
return PerformAsync(action, TimeSpan.FromMilliseconds(timeout), cancellationToken);
}
///
/// Perform the specified action with specified timeout
///
/// Action to run
/// Maximum timeout
/// True if the action finished whithout timing out
public static bool Perform(Action action, TimeSpan timeout)
{
return PerformAsync(action, timeout).GetAwaiter().GetResult();
}
public static async Task PerformAsync(Action action, TimeSpan timeout, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(action);
try
{
await Task.Run(action, cancellationToken).WaitAsync(timeout, cancellationToken);
return true;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return false;
}
catch (TimeoutException)
{
return false;
}
}
}
}