comparison 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
comparison
equal deleted inserted replaced
14:741981715d94 15:060f02cd4591
1 using System;
2 using System.Threading.Tasks;
3
4 namespace MetroWpf.Framework
5 {
6 public class ServiceClient
7 {
8 public static T Execute<T>(
9 Func<T> func,
10 int timeoutMilliseconds,
11 int maxAttempts)
12 {
13 T result;
14 Exception e;
15 TryExecute(func, timeoutMilliseconds, maxAttempts, out result, out e);
16 if (e != null) throw e;
17 return result;
18 }
19
20 public static bool TryExecute<T>(
21 Func<T> func,
22 int timeoutMilliseconds,
23 int maxAttempts,
24 out T result,
25 out Exception e)
26 {
27 bool isSuccessful = false;
28 var t = default(T);
29 e = null;
30
31 var task = Task.Factory.StartNew(() =>
32 {
33 for (int i = 0; i < maxAttempts; i++)
34 {
35 try { t = func(); }
36 catch { if (i == maxAttempts - 1) { throw; } }
37 }
38 });
39
40 try
41 {
42 task.Wait(timeoutMilliseconds);
43 if (!task.IsCompleted)
44 e = new TimeoutException();
45 else
46 isSuccessful = true;
47 }
48 catch (AggregateException ae)
49 {
50 e = ae.InnerException;
51 }
52
53 result = t;
54 return isSuccessful;
55 }
56 }
57 }