Merge pull request #409 from Alkarex/patch-1
[mono.git] / mcs / class / System.Threading.Tasks.Dataflow / System.Threading.Tasks.Dataflow / ReceiveBlock.cs
1 // ReceiveBlock.cs
2 //
3 // Copyright (c) 2011 Jérémie "garuma" Laval
4 // Copyright (c) 2012 Petr Onderka
5 //
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:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
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
22 // THE SOFTWARE.
23
24 namespace System.Threading.Tasks.Dataflow {
25         /// <summary>
26         /// This internal block is used by the <see cref="DataflowBlock.Receive"/> methods
27         /// to retrieve elements in either blocking or asynchronous way.
28         /// </summary>
29         class ReceiveBlock<TOutput> : ITargetBlock<TOutput> {
30                 readonly TaskCompletionSource<TOutput> completion =
31                         new TaskCompletionSource<TOutput> ();
32
33                 readonly CancellationToken token;
34                 CancellationTokenRegistration cancellationRegistration;
35                 readonly Timer timeoutTimer;
36
37                 IDisposable linkBridge;
38
39                 public ReceiveBlock (CancellationToken token, int timeout)
40                 {
41                         this.token = token;
42                         cancellationRegistration = token.Register (() =>
43                         {
44                                 lock (completion) {
45                                         completion.TrySetCanceled ();
46                                 }
47                                 CompletionSet ();
48                         });
49                         timeoutTimer = new Timer (
50                                 _ =>
51                                 {
52                                         lock (completion) {
53                                                 completion.TrySetException (new TimeoutException ());
54                                         }
55                                         CompletionSet ();
56                                 }, null, timeout,
57                                 Timeout.Infinite);
58                 }
59
60                 public DataflowMessageStatus OfferMessage (
61                         DataflowMessageHeader messageHeader, TOutput messageValue,
62                         ISourceBlock<TOutput> source, bool consumeToAccept)
63                 {
64                         if (!messageHeader.IsValid)
65                                 return DataflowMessageStatus.Declined;
66
67                         if (completion.Task.Status != TaskStatus.WaitingForActivation)
68                                 return DataflowMessageStatus.DecliningPermanently;
69
70                         lock (completion) {
71                                 if (completion.Task.Status != TaskStatus.WaitingForActivation)
72                                         return DataflowMessageStatus.DecliningPermanently;
73
74                                 if (consumeToAccept) {
75                                         bool consummed;
76                                         if (!source.ReserveMessage (messageHeader, this))
77                                                 return DataflowMessageStatus.NotAvailable;
78                                         messageValue = source.ConsumeMessage (messageHeader, this, out consummed);
79                                         if (!consummed)
80                                                 return DataflowMessageStatus.NotAvailable;
81                                 }
82
83                                 completion.TrySetResult (messageValue);
84                         }
85                         CompletionSet ();
86                         return DataflowMessageStatus.Accepted;
87                 }
88
89                 /// <summary>
90                 /// Synchronously waits until an item is available.
91                 /// </summary>
92                 /// <param name="bridge">The disposable object returned by <see cref="ISourceBlock{TOutput}.LinkTo"/>.</param>
93                 public TOutput WaitAndGet (IDisposable bridge)
94                 {
95                         try {
96                                 return AsyncGet (bridge).Result;
97                         } catch (AggregateException e) {
98                                 if (e.InnerException is TaskCanceledException)
99                                         throw new OperationCanceledException (token);
100                                 // resets the stack trace, but that shouldn't matter here
101                                 throw e.InnerException;
102                         }
103                 }
104
105                 /// <summary>
106                 /// Asynchronously waits until an item is available.
107                 /// </summary>
108                 /// <param name="bridge">The disposable object returned by <see cref="ISourceBlock{TOutput}.LinkTo"/>.</param>
109                 public Task<TOutput> AsyncGet (IDisposable bridge)
110                 {
111                         linkBridge = bridge;
112
113                         return completion.Task;
114                 }
115
116                 /// <summary>
117                 /// Called after the result has been set,
118                 /// cleans up after this block.
119                 /// </summary>
120                 void CompletionSet ()
121                 {
122                         if (linkBridge != null) {
123                                 linkBridge.Dispose ();
124                                 linkBridge = null;
125                         }
126
127                         cancellationRegistration.Dispose ();
128                         timeoutTimer.Dispose ();
129                 }
130
131                 public Task Completion {
132                         get { throw new NotSupportedException (); }
133                 }
134
135                 public void Complete ()
136                 {
137                         lock (completion) {
138                                 completion.TrySetException (new InvalidOperationException (
139                                         "No item could be received from the source."));
140                         }
141                         CompletionSet ();
142                 }
143
144                 public void Fault (Exception exception)
145                 {
146                         Complete ();
147                 }
148         }
149 }