Permalink
Browse files

TaskSample - ThreeItemsNoMatchExceptLastAsyncReturns

  • Loading branch information...
bobbymcr committed May 23, 2018
1 parent 71d532c commit 27d842922cb8bcf5df0771adac2908ba593f4605
@@ -26,21 +26,28 @@ public static async Task<T> FirstAsync<T>(this IEnumerable<Func<CancellationToke
Func<CancellationToken, Task<T>> match = async t =>
{
T result = await func(t);
if (pred(result))
T result = default(T);
try
{
result = await func(t);
if (pred(result))
{
firstResult = Tuple.Create(result);
cts.Cancel();
}
}
catch (Exception)
{
firstResult = Tuple.Create(result);
cts.Cancel();
}
return result;
};
Task<T> task = match(CancellationToken.None);
Task<T> task = match(cts.Token);
tasks.Add(task);
}
await Task.WhenAny(tasks);
await Task.WhenAll(tasks);
if (firstResult == null)
{
throw new InvalidOperationException("No matching result.");
@@ -129,11 +129,11 @@ public void TwoItemsSyncNoMatchesThrowsInvalidOperation()
[Fact]
public void TwoItemsFirstHangsUntilCancelSecondMatchesSyncReturns()
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
IEnumerable<Func<CancellationToken, Task<string>>> funcs = new Func<CancellationToken, Task<string>>[]
{
t =>
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
t.Register(() => tcs.SetCanceled());
return tcs.Task;
},
@@ -146,6 +146,37 @@ public void TwoItemsFirstHangsUntilCancelSecondMatchesSyncReturns()
task.Result.Should().Be("good 2");
}
[Fact]
public void ThreeItemsNoMatchExceptLastAsyncReturns()
{
TaskCompletionSource<string> tcs1 = new TaskCompletionSource<string>();
TaskCompletionSource<string> tcs2 = new TaskCompletionSource<string>();
TaskCompletionSource<string> tcs3 = new TaskCompletionSource<string>();
IEnumerable<Func<CancellationToken, Task<string>>> funcs = new Func<CancellationToken, Task<string>>[]
{
t => tcs1.Task,
t => tcs2.Task,
t => tcs3.Task
};
Task<string> task = funcs.FirstAsync(r => r.StartsWith("good", StringComparison.Ordinal));
task.IsCompleted.Should().BeFalse();
tcs1.SetResult("bad 1");
task.IsCompleted.Should().BeFalse();
tcs2.SetResult("bad 2");
task.IsCompleted.Should().BeFalse();
tcs3.SetResult("good 3");
task.IsCompletedSuccessfully.Should().BeTrue();
task.Result.Should().Be("good 3");
}
private static void ShouldBeFaulted(Task task)
{
task.IsCompleted.Should().BeTrue();

0 comments on commit 27d8429

Please sign in to comment.