Permalink
Browse files

TaskSample - OneItemThrowsSyncThrowsInvalidOperation

  • Loading branch information...
bobbymcr committed May 23, 2018
1 parent eb02ad6 commit fd8bd1b02d6a32256c80f578252a717570e7da68
@@ -14,7 +14,7 @@ public static class FuncTaskExtensions
public static async Task<T> FirstAsync<T>(this IEnumerable<Func<CancellationToken, Task<T>>> funcs, Predicate<T> pred)
{
var tasks = new List<Task<T>>();
T firstResult = default(T);
Tuple<T> firstResult = null;
using (CancellationTokenSource cts = new CancellationTokenSource())
{
foreach (Func<CancellationToken, Task<T>> func in funcs)
@@ -29,7 +29,7 @@ public static async Task<T> FirstAsync<T>(this IEnumerable<Func<CancellationToke
T result = await func(t);
if (pred(result))
{
firstResult = result;
firstResult = Tuple.Create(result);
cts.Cancel();
}
@@ -41,7 +41,12 @@ public static async Task<T> FirstAsync<T>(this IEnumerable<Func<CancellationToke
}
await Task.WhenAny(tasks);
return firstResult;
if (firstResult == null)
{
throw new InvalidOperationException("No matching result.");
}
return firstResult.Item1;
}
}
}
@@ -47,6 +47,23 @@ public void OneItemMatchesAsyncReturns()
task.Result.Should().Be("good");
}
[Fact]
public void OneItemThrowsSyncThrowsInvalidOperation()
{
IEnumerable<Func<CancellationToken, Task<string>>> funcs = new Func<CancellationToken, Task<string>>[]
{
t => { throw new BadImageFormatException("!!!"); }
};
Task<string> task = funcs.FirstAsync(r => true);
task.IsCompleted.Should().BeTrue();
task.Exception.Should().NotBeNull();
task.Exception.InnerException.Should()
.BeOfType<InvalidOperationException>().Which
.Message.Should().Be("No matching result.");
}
[Fact]
public void TwoItemsFirstMatchesSyncReturns()
{

0 comments on commit fd8bd1b

Please sign in to comment.