1 // OutputAvailableBlock.cs
3 // Copyright (c) 2011 Jérémie "garuma" Laval
4 // Copyright (c) 2012 Petr Onderka
6 // Permission is hereby granted, free of charge, to any person obtaining a copy
7 // of this software and associated documentation files (the "Software"), to deal
8 // in the Software without restriction, including without limitation the rights
9 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 // copies of the Software, and to permit persons to whom the Software is
11 // furnished to do so, subject to the following conditions:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 namespace System.Threading.Tasks.Dataflow {
26 /// This internal block is used by the <see cref="DataflowBlock.OutputAvailableAsync"/> methods
27 /// to check for available items in an asynchronous way.
29 class OutputAvailableBlock<TOutput> : ITargetBlock<TOutput> {
30 readonly TaskCompletionSource<bool> completion =
31 new TaskCompletionSource<bool> ();
32 IDisposable linkBridge;
33 CancellationTokenRegistration cancellationRegistration;
35 public DataflowMessageStatus OfferMessage (
36 DataflowMessageHeader messageHeader, TOutput messageValue,
37 ISourceBlock<TOutput> source, bool consumeToAccept)
39 if (!messageHeader.IsValid)
40 return DataflowMessageStatus.Declined;
42 if (completion.Task.Status != TaskStatus.WaitingForActivation)
43 return DataflowMessageStatus.DecliningPermanently;
45 completion.TrySetResult (true);
48 return DataflowMessageStatus.DecliningPermanently;
52 /// Returns a Task that can be used to wait until output from a block is available.
54 /// <param name="bridge">The disposable object returned by <see cref="ISourceBlock{TOutput}.LinkTo"/>.</param>
55 /// <param name="token">Cancellation token for this operation.</param>
56 public Task<bool> AsyncGet (IDisposable bridge, CancellationToken token)
59 cancellationRegistration = token.Register (() =>
61 completion.TrySetCanceled ();
65 return completion.Task;
69 /// Called after the result has been set,
70 /// cleans up after this block.
74 if (linkBridge != null) {
75 linkBridge.Dispose ();
79 cancellationRegistration.Dispose ();
82 public Task Completion {
83 get { throw new NotSupportedException (); }
86 public void Complete ()
88 completion.TrySetResult (false);
92 public void Fault (Exception exception)