Permalink
Browse files

TaskSample - cancel exactly once

  • Loading branch information...
bobbymcr committed May 23, 2018
1 parent cb81d9b commit 09eb8f11211f8f6a4635c79e557a83776433eee7
Showing with 10 additions and 3 deletions.
  1. +10 −3 projects/TaskSample/TaskSample.Core/Extensions/FuncTaskExtensions.cs
@@ -37,7 +37,7 @@ private sealed class MatchFunc<T> : IDisposable
private readonly CancellationTokenSource cts;
private readonly Predicate<T> pred;
private volatile Tuple<T> firstResult;
private Tuple<T> firstResult;
public MatchFunc(Predicate<T> pred)
{
@@ -67,8 +67,7 @@ public async Task RunAsync(Func<CancellationToken, Task<T>> func)
T result = await func(this.cts.Token);
if (this.pred(result))
{
this.firstResult = Tuple.Create(result);
this.cts.Cancel();
this.Complete(result);
}
}
catch (Exception)
@@ -80,6 +79,14 @@ public void Dispose()
{
this.cts.Dispose();
}
private void Complete(T result)
{
if (Interlocked.CompareExchange(ref this.firstResult, Tuple.Create(result), null) == null)
{
this.cts.Cancel();
}
}
}
}
}

0 comments on commit 09eb8f1

Please sign in to comment.