Mercurial > silverbladetech
diff MetroWpf/MetroWpf.Framework/ServiceClient.cs @ 15:060f02cd4591
Initial commit, pre airport work
author | stevenh7776 stevenhollidge@hotmail.com |
---|---|
date | Mon, 12 Mar 2012 23:05:21 +0800 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/MetroWpf/MetroWpf.Framework/ServiceClient.cs Mon Mar 12 23:05:21 2012 +0800 @@ -0,0 +1,57 @@ +using System; +using System.Threading.Tasks; + +namespace MetroWpf.Framework +{ + public class ServiceClient + { + public static T Execute<T>( + Func<T> func, + int timeoutMilliseconds, + int maxAttempts) + { + T result; + Exception e; + TryExecute(func, timeoutMilliseconds, maxAttempts, out result, out e); + if (e != null) throw e; + return result; + } + + public static bool TryExecute<T>( + Func<T> func, + int timeoutMilliseconds, + int maxAttempts, + out T result, + out Exception e) + { + bool isSuccessful = false; + var t = default(T); + e = null; + + var task = Task.Factory.StartNew(() => + { + for (int i = 0; i < maxAttempts; i++) + { + try { t = func(); } + catch { if (i == maxAttempts - 1) { throw; } } + } + }); + + try + { + task.Wait(timeoutMilliseconds); + if (!task.IsCompleted) + e = new TimeoutException(); + else + isSuccessful = true; + } + catch (AggregateException ae) + { + e = ae.InnerException; + } + + result = t; + return isSuccessful; + } + } +}