@@ -88,32 +88,28 @@ public async Task<T> TakeAsync()
8888 var taken = _pool ? . ReceiveAsync ( ( ts = new CancellationTokenSource ( ) ) . Token ) ;
8989 if ( taken != null )
9090 {
91- Task winner = null ;
9291 while ( taken . Status != TaskStatus . RanToCompletion )
9392 {
9493 // Ok we need to push into the pool...
9594 var generated = Generate ( out Task < T > actual ) ;
9695
97- // Allow for re-entrance here.
98- winner = await Task . WhenAny ( taken , generated ) ;
99- if ( winner == taken || generated . Result ) continue ; // ^^^ Check the status... Are we done? May need to generate another.
100-
101- // NOTE: Most of the time, only the above code is run. Below is the edge case that can occur when not able to add to the pool (full or disposed).
102-
103- // Was not added to pool? Uh-oh...
104- ts . Cancel ( ) ; // Since the generator failed or was unable to be added, then cancel waiting to recieve it.
105-
106- // Was it actually cancelled? If not then we skip this and
107- if ( await taken . ContinueWith ( t => t . IsCanceled ) ) // || t.IsFaulted ... .ReceiveAsync should never fault.
96+ if ( await Task . WhenAny ( taken , generated ) == generated && ! generated . Result )
10897 {
109- if ( actual . IsFaulted )
110- throw actual . Exception ; // Possible generator failure.
111- if ( actual . Status == TaskStatus . RanToCompletion )
112- return actual . Result ; // Don't let it go to waste.
113-
114- // This is a rare edge case where there's no fault but did not complete. Effectively erroneous.
115- Debug . Fail ( "Somehow the generate task did not complete and had no fault." ) ;
116- return _generator ( ) ;
98+ // ^^^ Not received yet and was not added to pool? Uh-oh...
99+ ts . Cancel ( ) ; // Since the generator failed or was unable to be added, then cancel waiting to recieve it.
100+
101+ // Was it actually cancelled?
102+ if ( await taken . ContinueWith ( t => t . IsCanceled ) ) // || t.IsFaulted ... .ReceiveAsync should never fault.
103+ {
104+ if ( actual . IsFaulted )
105+ throw actual . Exception ; // Possible generator failure.
106+ if ( actual . Status == TaskStatus . RanToCompletion )
107+ return actual . Result ; // Don't let it go to waste.
108+
109+ // This is a rare edge case where there's no fault but did not complete. Effectively erroneous.
110+ Debug . Fail ( "Somehow the generate task did not complete and had no fault." ) ;
111+ return _generator ( ) ;
112+ }
117113 }
118114 }
119115
0 commit comments