Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Retries the specified function a certin amount of times before throwing the exception
- /// </summary>
- /// <typeparam name="T">Result of the sucessfull function</typeparam>
- /// <param name="function">Function to excecute</param>
- /// <param name="maxTries">The maximum amount of attempts to exceute the function</param>
- /// <param name="timeoutMilliseconds">Timeout to wait for a function to finish execution</param>
- /// <returns></returns>
- public static T RetryOnFault<T>(Func<T> function,int maxTries,int timeoutMilliseconds = 0) {
- if(function == null)
- throw new ArgumentNullException("function");
- if(Math.Max(maxTries,0) == 0)
- throw new ArgumentOutOfRangeException("maxTries");
- for(int i = 0;i < maxTries;i++) {
- bool timedout = false;
- Exception error = null;
- T result = default(T);
- #if Net4
- //start a new task
- var t = Task.Factory
- .StartNew<T>(function);
- //for debugging
- t.ContinueWith((finnished) => Debug.WriteLine("Task: " + t.Id + " result: " + finnished.Result));
- //wait on the task for the specified time
- if(timeoutMilliseconds > 0)
- timedout = !t.Wait(timeoutMilliseconds);
- if(t.IsFaulted)
- error = t.Exception ?? new Exception("Unknown error");
- else
- result = t.Result;
- #else
- AutoResetEvent waitEvent = new AutoResetEvent(false);
- //queue up a worker thread
- ThreadPool.QueueUserWorkItem((state) => {
- try {
- result = ((Func<T>)state)();
- }
- catch(Exception ferror) {
- error = ferror;
- }
- finally {
- //resume back
- if(!waitEvent.SafeWaitHandle.IsClosed)
- waitEvent.Set();
- }
- },function);
- //wait on the task for the specified time
- timedout = !waitEvent.WaitOne(timeoutMilliseconds);
- waitEvent.Close();
- Debug.Write("Result: " + result);
- #endif
- //check if task faulted or timed out
- if(error != null || timedout) {
- if(timedout)
- error = new TimeoutException();
- Debug.WriteLine("Attempt " + (i + 1) + " failed: " + error.Message);
- //check how many errors
- if(i == maxTries - 1)
- throw error;
- }
- else
- return result;
- }
- //should never get here
- return default(T);
- }
Advertisement
Add Comment
Please, Sign In to add comment