#nullable enable using System; using System.Threading.Tasks; using Barotrauma; namespace EosInterfacePrivate; /// /// Creates a task that returns the result of a callback. /// This is meant to be used with EOS' asynchronous methods, /// which are all callback-based because this is a C library. /// internal class CallbackWaiter where T : notnull { private readonly object mutex = new object(); private Option result = Option.None; private readonly DateTime timeout; public readonly Task> Task; public CallbackWaiter(TimeSpan timeout = default) { this.timeout = DateTime.Now + (timeout == default ? TimeSpan.FromSeconds(60) : timeout); this.Task = System.Threading.Tasks.Task.Run(RunTask); } public void OnCompletion(ref T result) { lock (mutex) { this.result = Option.Some(result); } } private async Task> RunTask() { while (DateTime.Now < timeout) { lock (mutex) { if (result.IsSome()) { return result; } } await System.Threading.Tasks.Task.Delay(32); } return Option.None; } }