/// <summary> /// Tries the specified action until the result of the action is not equal to <c>default{T}</c> /// or the time out is reached. /// </summary> /// <typeparam name="T">The result type of the action</typeparam> /// <param name="func">The action.</param> /// <returns>The result of the action of <c>default{T}</c> when time out occured.</returns> public T Try <T>(DoFunc <T> func) { if (func == null) { throw new ArgumentNullException("func"); } var defaultT = default(T); var timeoutTimer = GetTimer(); do { LastException = null; try { var result = func.Invoke(); if (!result.Equals(defaultT)) { return(result); } } catch (Exception e) { LastException = e; } Sleep(SleepTime); } while (!timeoutTimer.Elapsed); HandleTimeOut(); return(defaultT); }
private void AddToAttributeCache <T>(string key, DoFunc <T> function) { if (!AttributeCache.ContainsKey(key)) { AttributeCache.Add(key, function.Invoke()); } }
public static T TryFuncIgnoreException <T>(DoFunc <T> func) { try { return(func.Invoke()); } catch { return(default(T)); } }
/// <summary> /// Tries the specified action until the result of the action is not equal to <c>default{T}</c> /// or the time out is reached. /// </summary> /// <typeparam name="T">The result type of the action</typeparam> /// <param name="func">The action.</param> /// <returns>The result of the action of <c>default{T}</c> when time out occured.</returns> public T Try <T>(DoFunc <T> func) { if (func == null) { throw new ArgumentNullException("func"); } var timeoutTimer = GetTimer(); var currentSleepTime = TimeSpan.FromMilliseconds(1); do { LastException = null; try { var result = func.Invoke(); if (!Equals(result, default(T))) { return(result); } } catch (Exception e) { LastException = e; } Sleep(currentSleepTime); currentSleepTime += currentSleepTime; if (currentSleepTime > SleepTime) { currentSleepTime = SleepTime; } } while (!timeoutTimer.Elapsed); HandleTimeOut(); return(default(T)); }
public static T TryFuncFailOver <T>(DoFunc <T> func, int numberOfRetries, int sleepTime) { Exception LastException; do { try { var result = func.Invoke(); return(result); } catch (Exception e) { LastException = e; } numberOfRetries -= 1; Thread.Sleep(sleepTime); } while (numberOfRetries != 0); throw LastException; }