diff --git a/Implab/PromiseExtensions.cs b/Implab/PromiseExtensions.cs --- a/Implab/PromiseExtensions.cs +++ b/Implab/PromiseExtensions.cs @@ -72,6 +72,23 @@ namespace Implab { } }; } + + static void CancelCallback(object cookie) { + ((ICancellable)cookie).Cancel(); + } + + /// + /// Cancells promise after the specified timeout is elapsed. + /// + /// The promise to cancel on timeout. + /// The timeout in milliseconds. + /// The 1st type parameter. + public static TPromise Timeout(this TPromise that, int milliseconds) where TPromise : IPromise { + Safe.ArgumentNotNull(that, "that"); + var timer = new Timer(CancelCallback, that, milliseconds, -1); + that.On(timer.Dispose, PromiseEventType.All); + return that; + } #if NET_4_5