Minecraft-Console-Client/MinecraftClient/AutoTimeout.cs
breadbyte d9f1a77ac2
.NET 5+ Support (#1674)
Implement changes to support .NET 5 onwards.
Co-authored-by: ReinforceZwei <39955851+ReinforceZwei@users.noreply.github.com>
Co-authored-by: ORelio <ORelio@users.noreply.github.com>
2022-07-03 22:34:07 +08:00

44 lines
No EOL
1.4 KiB
C#

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace MinecraftClient
{
/// <summary>
/// Allow easy timeout on pieces of code
/// </summary>
/// <remarks>
/// By ORelio - (c) 2014 - CDDL 1.0
/// </remarks>
public class AutoTimeout
{
/// <summary>
/// Perform the specified action with specified timeout
/// </summary>
/// <param name="action">Action to run</param>
/// <param name="timeout">Maximum timeout in milliseconds</param>
/// <returns>True if the action finished whithout timing out</returns>
public static bool Perform(Action action, int timeout)
{
return Perform(action, TimeSpan.FromMilliseconds(timeout));
}
/// <summary>
/// Perform the specified action with specified timeout
/// </summary>
/// <param name="action">Action to run</param>
/// <param name="timeout">Maximum timeout</param>
/// <returns>True if the action finished whithout timing out</returns>
public static bool Perform(Action action, TimeSpan timeout) {
Thread thread = new Thread(new ThreadStart(action));
thread.Start();
bool success = thread.Join(timeout);
if (!success)
thread.Interrupt();
thread = null;
return success;
}
}
}