Skip to content

Instantly share code, notes, and snippets.

@lmatt-bit
Created April 3, 2016 06:26
Show Gist options
  • Select an option

  • Save lmatt-bit/76f711b8fa5e4673a91080a18ec86e47 to your computer and use it in GitHub Desktop.

Select an option

Save lmatt-bit/76f711b8fa5e4673a91080a18ec86e47 to your computer and use it in GitHub Desktop.
Test Async in CSharp
class Program
{
static async Task DoSomethingAsync()
{
int val = 13;
await Task.Delay(TimeSpan.FromSeconds(1));
val *= 2;
await Task.Delay(TimeSpan.FromSeconds(1));
Console.Out.WriteLine(val);
}
static async Task<string> DownloadStringWithRetries(string uri)
{
using (var client = new HttpClient())
{
var nextDelay = TimeSpan.FromSeconds(1);
for(int i = 0; i < 3; i++)
{
try
{
return await client.GetStringAsync(uri);
}
catch
{
}
await Task.Delay(nextDelay);
nextDelay = nextDelay + nextDelay;
}
return await client.GetStringAsync(uri);
}
}
static async Task<string> DownloadStringWithTimeOut(string uri, int timeout)
{
using (var client = new HttpClient())
{
var downloadTask = client.GetStringAsync(uri);
var timeoutTask = Task.Delay(timeout);
var completedTask = await Task.WhenAny(downloadTask, timeoutTask);
if (timeoutTask == completedTask)
{
return null;
}
else
{
return await downloadTask;
}
}
}
static async Task<int> DelayAndReturnAsync(int val)
{
await Task.Delay(TimeSpan.FromSeconds(val));
return val;
}
static async Task ProcessTasksAsync()
{
var taskA = DelayAndReturnAsync(2);
var taskB = DelayAndReturnAsync(3);
var taskC = DelayAndReturnAsync(1);
var tasks = new[] { taskA, taskB, taskC };
var stopWatch = Stopwatch.StartNew();
foreach (var task in tasks)
{
var result = await task;
stopWatch.Stop();
Console.Out.WriteLine("{0}={1}", stopWatch.Elapsed, result);
stopWatch.Restart();
}
}
static void Main(string[] args)
{
//var result = DownloadStringWithRetries("http://www.baidu.com").Result;
//Console.Out.WriteLine(result);
//var result = DownloadStringWithTimeOut("http://www.baidu.com", 10).Result;
//Console.Out.WriteLine(result == null);
ProcessTasksAsync().Wait();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment