Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Created December 5, 2012 18:16
Show Gist options
  • Save davidfowl/4218095 to your computer and use it in GitHub Desktop.
Save davidfowl/4218095 to your computer and use it in GitHub Desktop.
Async for fun
static IEnumerable<Task> DoItAsync()
{
yield return Task.Delay(1000);
yield return Task.Run(() => 1 + 1);
Console.WriteLine("hello");
}
public static Task AsyncEnumerator(Func<IEnumerable<Task>> taskChainFactory)
{
var tcs = new TaskCompletionSource<object>();
var enumerator = taskChainFactory().GetEnumerator();
AsyncEnumeratorImpl(tcs, enumerator);
return tcs.Task;
}
private static void AsyncEnumeratorImpl(TaskCompletionSource<object> tcs, IEnumerator<Task> enumerator)
{
while (enumerator.MoveNext())
{
Task task = enumerator.Current;
if (task.IsCompleted)
{
try
{
task.Wait();
}
catch(Exception ex)
{
tcs.TrySetException(ex);
}
}
else
{
ContinueAsync(tcs, enumerator, task);
return;
}
}
tcs.TrySetResult(null);
}
private static void ContinueAsync(TaskCompletionSource<object> tcs, IEnumerator<Task> enumerator, Task task)
{
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
tcs.TrySetException(t.Exception);
}
else if (t.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
AsyncEnumeratorImpl(tcs, enumerator);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment