Created
December 5, 2012 18:16
-
-
Save davidfowl/4218095 to your computer and use it in GitHub Desktop.
Async for fun
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
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