diff --git a/src/chocolatey/chocolatey.csproj b/src/chocolatey/chocolatey.csproj index 16715dd371..6cc912604b 100644 --- a/src/chocolatey/chocolatey.csproj +++ b/src/chocolatey/chocolatey.csproj @@ -78,6 +78,7 @@ Properties\SolutionVersion.cs + diff --git a/src/chocolatey/infrastructure/commands/Execute.cs b/src/chocolatey/infrastructure/commands/Execute.cs new file mode 100644 index 0000000000..a64640d15e --- /dev/null +++ b/src/chocolatey/infrastructure/commands/Execute.cs @@ -0,0 +1,95 @@ +// Copyright © 2011 - Present RealDimensions Software, LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace chocolatey.infrastructure.commands +{ + using System; + using System.Threading.Tasks; + + /// + /// Execute a method or function + /// + public sealed class Execute + { + private readonly TimeSpan _timespan; + + /// + /// The number of seconds to wait for an operation to complete. + /// + /// The timeout in seconds. + /// + public static Execute with_timeout(int timeoutInSeconds) + { + return new Execute(TimeSpan.FromSeconds(timeoutInSeconds)); + } + + /// + /// The timespan to wait for an operation to complete. + /// + /// The timeout. + /// + public static Execute with_timeout(TimeSpan timeout) + { + return new Execute(timeout); + } + + private Execute(TimeSpan timespan) + { + _timespan = timespan; + } + + /// + /// Runs an operation with a timeout. + /// + /// The type to return + /// The function to execute. + /// The timeout default value. + /// The results of the function if completes within timespan, otherwise returns the default value. + public T command(Func function, T timeoutDefaultValue) + { + if (function == null) return timeoutDefaultValue; + + var task = Task.Factory.StartNew(function); + task.Wait(_timespan); + + if (task.IsCompleted) return task.Result; + return timeoutDefaultValue; + + //T result = timeoutDefaultValue; + //var thread = new Thread(() => result = function()); + //thread.Start(); + + //bool completed = thread.Join((int)TimeSpan.FromSeconds(timeoutInSeconds).TotalMilliseconds); + //if (!completed) thread.Abort(); + + //return result; + } + + /// + /// Calls a method with a timeout. + /// + /// The action to perform. + /// True if it finishes executing, false otherwise. + public bool command(Action action) + { + if (action == null) return false; + + var task = Task.Factory.StartNew(action); + task.Wait(_timespan); + + return task.IsCompleted; + } + } +}