Skip to content

Instantly share code, notes, and snippets.

@georgebearden
Created May 19, 2016 01:58
Show Gist options
  • Save georgebearden/31f965eba3ad712af6932afdb2783fea to your computer and use it in GitHub Desktop.
Save georgebearden/31f965eba3ad712af6932afdb2783fea to your computer and use it in GitHub Desktop.
using System;
using Newtonsoft.Json;
using System.Reactive.Linq;
using Nito.AsyncEx;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using System.Reactive.Threading.Tasks;
namespace Playground
{
class MainClass
{
public static void Main (string[] args)
{
try
{
AsyncContext.Run(() => MainAsync(args));
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
}
public static async Task MainAsync(string[] args)
{
try
{
await Task.Delay (TimeSpan.FromSeconds(5)).TimeoutAfter (TimeSpan.FromSeconds (1));
}
catch (TimeoutException)
{
}
// just an example.
var result = await GetIntAsync ()
.TimeoutAfter ()
.ToObservable ()
.Catch<int, TimeoutException> (ex => {
Console.WriteLine(ex);
return Observable.Return<int> (0);
})
.FirstAsync ();
}
public static async Task<int> GetIntAsync()
{
await Task.Delay (TimeSpan.Zero);
return 1;
}
}
public static class TaskExtensions {
public static async Task TimeoutAfter(this Task task) {
await task.TimeoutAfter (TimeSpan.FromSeconds (1));
}
public static async Task TimeoutAfter(this Task task, TimeSpan timeout) {
var cts = new CancellationTokenSource();
var completed = await Task.WhenAny(task, Task.Delay(timeout, cts.Token));
if (completed == task) {
cts.Cancel();
await task;
} else {
throw new TimeoutException("Task timed out.");
}
}
public static async Task<T> TimeoutAfter<T>(this Task<T> task) {
return await task.TimeoutAfter (TimeSpan.FromSeconds (1));
}
public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout) {
var cts = new CancellationTokenSource();
var completed = await Task.WhenAny(task, Task.Delay(timeout, cts.Token));
if (completed == task) {
cts.Cancel();
return await task;
} else {
throw new TimeoutException("Task timed out.");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment