Created
October 28, 2015 00:00
-
-
Save sajayantony/bee14b0ee7bd7d5c5c3b to your computer and use it in GitHub Desktop.
TimeBoxTaskExtension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net.Http; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace TestDistinch | |
{ | |
static class TimeBoxTaskExtensions | |
{ | |
public const int DefaultTimeoutMilliseconds = 200; | |
public static TimeSpan DefaultTimeout = TimeSpan.FromMilliseconds(DefaultTimeoutMilliseconds); | |
public static string DefaultTimeoutString = string.Format("{0:hh\\:mm\\:ss\\:fff}", DefaultTimeout); | |
public static async Task<T> TimeBox<T>(this Task<T> t, string operationName) | |
{ | |
var timeoutTask = Task.Delay(DefaultTimeout); | |
var completed = await Task.WhenAny(t, timeoutTask); | |
if (completed == timeoutTask) | |
{ | |
throw new TimeoutException(String.Format( | |
"Operation {0} did not complete in {1} the specified interval", | |
operationName, | |
DefaultTimeoutString)); | |
} | |
else | |
{ | |
return t.Result; | |
} | |
} | |
} | |
class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
Run(); | |
Console.ReadLine(); | |
} | |
static async void Run() | |
{ | |
for (int i = 0; i < 100; i++) | |
{ | |
try | |
{ | |
var result = await Test(i * 10).TimeBox("Ping" + i); | |
Console.WriteLine("Completed " + i); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
} | |
} | |
static async Task<string> Test(int sleep) | |
{ | |
HttpClient client = new HttpClient(); | |
var t = client.GetStringAsync("http://bing.com"); | |
var value = await t; | |
Thread.Sleep(sleep); | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment