├── .gitignore ├── LICENSE ├── Properties └── AssemblyInfo.cs ├── StreamExtensions.cs ├── System.Collections.Concurrent.Partitioners ├── EnumerablePartitioner.cs ├── ListPartitioner.cs └── UserRangePartitioner.cs ├── System.Collections.Concurrent ├── BlockingCollection.cs ├── ConcurrentBag.cs ├── ConcurrentDictionary.cs ├── ConcurrentOrderedList.cs ├── ConcurrentQueue.cs ├── ConcurrentStack.cs ├── IProducerConsumerCollection.cs ├── OrderablePartitioner.cs ├── Partitioner.cs └── SplitOrderedList.cs ├── System.Collections.Generic ├── CollectionDebuggerView.cs ├── DefaultEqualityComparer.cs └── GenericEqualityComparer.cs ├── System.Collections ├── IStructuralComparable.cs └── IStructuralEquatable.cs ├── System.Runtime.CompilerServices ├── AsyncStateMachineAttribute.cs ├── AsyncTaskMethodBuilder.cs ├── AsyncTaskMethodBuilder_T.cs ├── AsyncVoidMethodBuilder.cs ├── ConfiguredTaskAwaitable.cs ├── ConfiguredTaskAwaitable_T.cs ├── IAsyncStateMachine.cs ├── ICriticalNotifyCompletion.cs ├── INotifyCompletion.cs ├── StateMachineAttribute.cs ├── TaskAwaiter.cs ├── TaskAwaiter_T.cs └── YieldAwaitable.cs ├── System.Runtime.ExceptionServices └── ExceptionDispatchInfo.cs ├── System.Runtime.Remoting.Messaging └── AsyncResult.cs ├── System.Threading.Tasks.Net35.csproj ├── System.Threading.Tasks.Unity.csproj ├── System.Threading.Tasks ├── CyclicDeque.cs ├── IConcurrentDeque.cs ├── PopResult.cs ├── SynchronizationContextScheduler.cs ├── Task.cs ├── TaskActionInvoker.cs ├── TaskCanceledException.cs ├── TaskCompletionQueue.cs ├── TaskCompletionSource.cs ├── TaskConstants.cs ├── TaskConstants_T.cs ├── TaskContinuation.cs ├── TaskContinuationOptions.cs ├── TaskCreationOptions.cs ├── TaskDebuggerView.cs ├── TaskExceptionSlot.cs ├── TaskExtensions.cs ├── TaskExtensionsImpl.cs ├── TaskFactory.cs ├── TaskFactory_T.cs ├── TaskScheduler.cs ├── TaskSchedulerException.cs ├── TaskStatus.cs ├── Task_T.cs ├── TpScheduler.cs └── UnobservedTaskExceptionEventArgs.cs ├── System.Threading ├── AtomicBoolean.cs ├── CancellationToken.cs ├── CancellationTokenRegistration.cs ├── CancellationTokenSource.cs ├── CountdownEvent.cs ├── ManualResetEventSlim.cs ├── SpinWait.cs └── Watch.cs ├── System ├── AggregateException.cs ├── Funcs.cs ├── Lazy.cs ├── LazyThreadSafetyMode.cs ├── LocalDataStoreSlot.cs ├── OperationCanceledException.cs ├── Tuple.cs └── Tuples.cs └── UnityExt.cs /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | obj 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Couchbase Third-Party Dependency Mirrors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // 2 | // AssemblyInfo.cs 3 | // 4 | // Author: 5 | // Jim Borden 6 | // 7 | // Copyright (c) 2015 Couchbase, Inc All rights reserved. 8 | // 9 | // Licensed under the Apache License, Version 2.0 (the "License"); 10 | // you may not use this file except in compliance with the License. 11 | // You may obtain a copy of the License at 12 | // 13 | // http://www.apache.org/licenses/LICENSE-2.0 14 | // 15 | // Unless required by applicable law or agreed to in writing, software 16 | // distributed under the License is distributed on an "AS IS" BASIS, 17 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | // See the License for the specific language governing permissions and 19 | // limitations under the License. 20 | // 21 | using System.Reflection; 22 | using System.Runtime.CompilerServices; 23 | 24 | // Information about this assembly is defined by the following attributes. 25 | // Change them to the values specific to your project. 26 | 27 | [assembly: AssemblyTitle("System.Threading.Tasks.Net35")] 28 | [assembly: AssemblyDescription("The Task Parallel Library ported back to .NET 3.5")] 29 | [assembly: AssemblyCompany ("Couchbase")] 30 | [assembly: AssemblyProduct("TPL .NET 3.5")] 31 | [assembly: AssemblyCopyright("2015")] 32 | 33 | // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". 34 | // The form "{Major}.{Minor}.*" will automatically update the build and revision, 35 | // and "{Major}.{Minor}.{Build}.*" will update just the revision. 36 | 37 | [assembly: AssemblyVersion("1.0.0.0")] 38 | -------------------------------------------------------------------------------- /System.Collections.Concurrent.Partitioners/EnumerablePartitioner.cs: -------------------------------------------------------------------------------- 1 | // 2 | // EnumerablePartitioner.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2009 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System; 28 | using System.Collections.Generic; 29 | 30 | namespace System.Collections.Concurrent.Partitioners 31 | { 32 | // Represent a chunk partitioner 33 | internal class EnumerablePartitioner : OrderablePartitioner 34 | { 35 | IEnumerable source; 36 | 37 | const int InitialPartitionSize = 1; 38 | const int PartitionMultiplier = 2; 39 | 40 | int initialPartitionSize; 41 | int partitionMultiplier; 42 | 43 | public EnumerablePartitioner (IEnumerable source) 44 | : this (source, InitialPartitionSize, PartitionMultiplier) 45 | { 46 | 47 | } 48 | 49 | // This is used to get striped partitionning (for Take and Skip for instance 50 | public EnumerablePartitioner (IEnumerable source, int initialPartitionSize, int partitionMultiplier) 51 | : base (true, false, true) 52 | { 53 | this.source = source; 54 | this.initialPartitionSize = initialPartitionSize; 55 | this.partitionMultiplier = partitionMultiplier; 56 | } 57 | 58 | public override IList>> GetOrderablePartitions (int partitionCount) 59 | { 60 | if (partitionCount <= 0) 61 | throw new ArgumentOutOfRangeException ("partitionCount"); 62 | 63 | IEnumerator>[] enumerators 64 | = new IEnumerator>[partitionCount]; 65 | 66 | PartitionerState state = new PartitionerState (); 67 | IEnumerator src = source.GetEnumerator (); 68 | bool isSimple = initialPartitionSize == 1 && partitionMultiplier == 1; 69 | 70 | for (int i = 0; i < enumerators.Length; i++) { 71 | enumerators[i] = isSimple ? GetPartitionEnumeratorSimple (src, state, i == enumerators.Length - 1) : GetPartitionEnumerator (src, state); 72 | } 73 | 74 | return enumerators; 75 | } 76 | 77 | // This partitioner that is simpler than the general case (don't use a list) is called in the case 78 | // of initialPartitionSize == partitionMultiplier == 1 79 | IEnumerator> GetPartitionEnumeratorSimple (IEnumerator src, 80 | PartitionerState state, 81 | bool last) 82 | { 83 | long index = -1; 84 | var value = default (T); 85 | 86 | try { 87 | do { 88 | lock (state.SyncLock) { 89 | if (state.Finished) 90 | break; 91 | if (state.Finished = !src.MoveNext ()) 92 | break; 93 | 94 | index = state.Index++; 95 | value = src.Current; 96 | } 97 | 98 | yield return new KeyValuePair (index, value); 99 | } while (!state.Finished); 100 | } finally { 101 | if (last) 102 | src.Dispose (); 103 | } 104 | } 105 | 106 | IEnumerator> GetPartitionEnumerator (IEnumerator src, PartitionerState state) 107 | { 108 | int count = initialPartitionSize; 109 | List list = new List (); 110 | 111 | while (!state.Finished) { 112 | list.Clear (); 113 | long ind = -1; 114 | 115 | lock (state.SyncLock) { 116 | if (state.Finished) 117 | break; 118 | 119 | ind = state.Index; 120 | 121 | for (int i = 0; i < count; i++) { 122 | if (state.Finished = !src.MoveNext ()) { 123 | if (list.Count == 0) 124 | yield break; 125 | else 126 | break; 127 | } 128 | 129 | list.Add (src.Current); 130 | state.Index++; 131 | } 132 | } 133 | 134 | for (int i = 0; i < list.Count; i++) 135 | yield return new KeyValuePair (ind + i, list[i]); 136 | 137 | count *= partitionMultiplier; 138 | } 139 | } 140 | 141 | class PartitionerState 142 | { 143 | public bool Finished; 144 | public long Index = 0; 145 | public readonly object SyncLock = new object (); 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /System.Collections.Concurrent.Partitioners/ListPartitioner.cs: -------------------------------------------------------------------------------- 1 | // 2 | // ListPartitioner.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2009 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System; 28 | using System.Collections.Generic; 29 | 30 | namespace System.Collections.Concurrent.Partitioners 31 | { 32 | // Represent a Range partitioner 33 | internal class ListPartitioner : OrderablePartitioner 34 | { 35 | IList source; 36 | 37 | public ListPartitioner (IList source) : base (true, true, true) 38 | { 39 | this.source = source; 40 | } 41 | 42 | public override IList>> GetOrderablePartitions (int partitionCount) 43 | { 44 | if (partitionCount <= 0) 45 | throw new ArgumentOutOfRangeException ("partitionCount"); 46 | 47 | IEnumerator>[] enumerators 48 | = new IEnumerator>[partitionCount]; 49 | 50 | int count = source.Count / partitionCount; 51 | int extra = 0; 52 | 53 | if (source.Count < partitionCount) { 54 | count = 1; 55 | } else { 56 | extra = source.Count % partitionCount; 57 | if (extra > 0) 58 | ++count; 59 | } 60 | 61 | int currentIndex = 0; 62 | 63 | Range[] ranges = new Range[enumerators.Length]; 64 | for (int i = 0; i < ranges.Length; i++) { 65 | ranges[i] = new Range (currentIndex, 66 | currentIndex + count); 67 | currentIndex += count; 68 | if (--extra == 0) 69 | --count; 70 | } 71 | 72 | for (int i = 0; i < enumerators.Length; i++) { 73 | enumerators[i] = GetEnumeratorForRange (ranges, i); 74 | } 75 | 76 | return enumerators; 77 | } 78 | 79 | class Range 80 | { 81 | public int Actual; 82 | public readonly int LastIndex; 83 | 84 | public Range (int frm, int lastIndex) 85 | { 86 | Actual = frm; 87 | LastIndex = lastIndex; 88 | } 89 | } 90 | 91 | IEnumerator> GetEnumeratorForRange (Range[] ranges, int workerIndex) 92 | { 93 | if (ranges[workerIndex].Actual >= source.Count) 94 | return GetEmpty (); 95 | 96 | return GetEnumeratorForRangeInternal (ranges, workerIndex); 97 | } 98 | 99 | IEnumerator> GetEmpty () 100 | { 101 | yield break; 102 | } 103 | 104 | IEnumerator> GetEnumeratorForRangeInternal (Range[] ranges, int workerIndex) 105 | { 106 | Range range = ranges[workerIndex]; 107 | int lastIndex = range.LastIndex; 108 | int index = range.Actual; 109 | 110 | for (int i = index; i < lastIndex; i = ++range.Actual) { 111 | yield return new KeyValuePair (i, source[i]); 112 | } 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /System.Collections.Concurrent.Partitioners/UserRangePartitioner.cs: -------------------------------------------------------------------------------- 1 | // 2 | // UserRangePartitioner.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2010 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System; 28 | using System.Threading; 29 | using System.Collections.Generic; 30 | 31 | namespace System.Collections.Concurrent.Partitioners 32 | { 33 | internal class UserRangePartitioner : OrderablePartitioner> 34 | { 35 | readonly int start; 36 | readonly int end; 37 | readonly int rangeSize; 38 | 39 | public UserRangePartitioner (int start, int end, int rangeSize) : base (true, true, true) 40 | { 41 | this.start = start; 42 | this.end = end; 43 | this.rangeSize = rangeSize; 44 | } 45 | 46 | public override IList>>> GetOrderablePartitions (int partitionCount) 47 | { 48 | if (partitionCount <= 0) 49 | throw new ArgumentOutOfRangeException ("partitionCount"); 50 | 51 | int currentIndex = 0; 52 | Func getNextIndex = () => Interlocked.Increment (ref currentIndex) - 1; 53 | 54 | var enumerators = new IEnumerator>>[partitionCount]; 55 | for (int i = 0; i < partitionCount; i++) 56 | enumerators[i] = GetEnumerator (getNextIndex); 57 | 58 | return enumerators; 59 | } 60 | 61 | IEnumerator>> GetEnumerator (Func getNextIndex) 62 | { 63 | while (true) { 64 | int index = getNextIndex (); 65 | int sliceStart = index * rangeSize + start; 66 | 67 | if (sliceStart >= end) 68 | break; 69 | 70 | yield return new KeyValuePair> (index, Tuple.Create (sliceStart, Math.Min (end, sliceStart + rangeSize))); 71 | sliceStart += rangeSize; 72 | } 73 | } 74 | } 75 | 76 | internal class UserLongRangePartitioner : OrderablePartitioner> 77 | { 78 | readonly long start; 79 | readonly long end; 80 | readonly long rangeSize; 81 | 82 | public UserLongRangePartitioner (long start, long end, long rangeSize) : base (true, true, true) 83 | { 84 | this.start = start; 85 | this.end = end; 86 | this.rangeSize = rangeSize; 87 | } 88 | 89 | public override IList>>> GetOrderablePartitions (int partitionCount) 90 | { 91 | if (partitionCount <= 0) 92 | throw new ArgumentOutOfRangeException ("partitionCount"); 93 | 94 | long currentIndex = 0; 95 | Func getNextIndex = () => Interlocked.Increment (ref currentIndex) - 1; 96 | 97 | var enumerators = new IEnumerator>>[partitionCount]; 98 | for (int i = 0; i < partitionCount; i++) 99 | enumerators[i] = GetEnumerator (getNextIndex); 100 | 101 | return enumerators; 102 | } 103 | 104 | IEnumerator>> GetEnumerator (Func getNextIndex) 105 | { 106 | while (true) { 107 | long index = getNextIndex (); 108 | long sliceStart = index * rangeSize + start; 109 | 110 | if (sliceStart >= end) 111 | break; 112 | 113 | yield return new KeyValuePair> (index, Tuple.Create (sliceStart, Math.Min (end, sliceStart + rangeSize))); 114 | sliceStart += rangeSize; 115 | } 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /System.Collections.Concurrent/ConcurrentBag.cs: -------------------------------------------------------------------------------- 1 | // 2 | // ConcurrentBag.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2009 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System; 28 | using System.Collections; 29 | using System.Collections.Generic; 30 | using System.Diagnostics; 31 | using System.Runtime.InteropServices; 32 | 33 | using System.Threading; 34 | using System.Threading.Tasks; 35 | 36 | namespace System.Collections.Concurrent 37 | { 38 | [ComVisible (false)] 39 | [DebuggerDisplay ("Count={Count}")] 40 | [DebuggerTypeProxy (typeof (CollectionDebuggerView<>))] 41 | public class ConcurrentBag : IProducerConsumerCollection, IEnumerable, IEnumerable 42 | { 43 | // We store hints in an int 44 | int hints; 45 | 46 | int count; 47 | // The container area is where bag are added foreach thread 48 | ConcurrentDictionary> container = new ConcurrentDictionary> (); 49 | // The staging area is where non-empty bag are located for fast iteration 50 | ConcurrentDictionary> staging = new ConcurrentDictionary> (); 51 | 52 | public ConcurrentBag () 53 | { 54 | } 55 | 56 | public ConcurrentBag (IEnumerable collection) : this () 57 | { 58 | foreach (T item in collection) 59 | Add (item); 60 | } 61 | 62 | public void Add (T item) 63 | { 64 | int index; 65 | CyclicDeque bag = GetBag (out index); 66 | bag.PushBottom (item); 67 | staging.TryAdd (index, bag); 68 | AddHint (index); 69 | Interlocked.Increment (ref count); 70 | } 71 | 72 | bool IProducerConsumerCollection.TryAdd (T element) 73 | { 74 | Add (element); 75 | return true; 76 | } 77 | 78 | public bool TryTake (out T result) 79 | { 80 | result = default (T); 81 | 82 | if (count == 0) 83 | return false; 84 | 85 | int hintIndex; 86 | CyclicDeque bag = GetBag (out hintIndex, false); 87 | bool ret = true; 88 | 89 | if (bag == null || bag.PopBottom (out result) != PopResult.Succeed) { 90 | var self = bag; 91 | ret = false; 92 | foreach (var other in staging) { 93 | // Try to retrieve something based on a hint 94 | ret = TryGetHint (out hintIndex) && (bag = container[hintIndex]).PopTop (out result) == PopResult.Succeed; 95 | 96 | // We fall back to testing our slot 97 | if (!ret && other.Value != self) { 98 | var status = other.Value.PopTop (out result); 99 | while (status == PopResult.Abort) 100 | status = other.Value.PopTop (out result); 101 | ret = status == PopResult.Succeed; 102 | hintIndex = other.Key; 103 | bag = other.Value; 104 | } 105 | 106 | // If we found something, stop 107 | if (ret) 108 | break; 109 | } 110 | } 111 | 112 | if (ret) { 113 | TidyBag (hintIndex, bag); 114 | Interlocked.Decrement (ref count); 115 | } 116 | 117 | return ret; 118 | } 119 | 120 | public bool TryPeek (out T result) 121 | { 122 | result = default (T); 123 | 124 | if (count == 0) 125 | return false; 126 | 127 | int hintIndex; 128 | CyclicDeque bag = GetBag (out hintIndex, false); 129 | bool ret = true; 130 | 131 | if (bag == null || !bag.PeekBottom (out result)) { 132 | var self = bag; 133 | ret = false; 134 | foreach (var other in staging) { 135 | // Try to retrieve something based on a hint 136 | ret = TryGetHint (out hintIndex) && container[hintIndex].PeekTop (out result); 137 | 138 | // We fall back to testing our slot 139 | if (!ret && other.Value != self) 140 | ret = other.Value.PeekTop (out result); 141 | 142 | // If we found something, stop 143 | if (ret) 144 | break; 145 | } 146 | } 147 | 148 | return ret; 149 | } 150 | 151 | void AddHint (int index) 152 | { 153 | // We only take thread index that can be stored in 5 bits (i.e. thread ids 1-15) 154 | if (index > 0xF) 155 | return; 156 | var hs = hints; 157 | // If cas failed then we don't retry 158 | Interlocked.CompareExchange (ref hints, (int)(((uint)hs) << 4 | (uint)index), (int)hs); 159 | } 160 | 161 | bool TryGetHint (out int index) 162 | { 163 | /* Funny little thing to know, since hints is signed (because CAS has no uint overload), 164 | * a shift-right operation is an arithmetic shift which might set high-order right bits 165 | * to 1 instead of 0 if the number turns negative. 166 | */ 167 | var hs = hints; 168 | index = 0; 169 | 170 | if (Interlocked.CompareExchange (ref hints, (int)(((uint)hs) >> 4), hs) == hs) 171 | index = (int)(hs & 0xF); 172 | 173 | return index > 0; 174 | } 175 | 176 | public int Count { 177 | get { 178 | return count; 179 | } 180 | } 181 | 182 | public bool IsEmpty { 183 | get { 184 | return count == 0; 185 | } 186 | } 187 | 188 | object System.Collections.ICollection.SyncRoot { 189 | get { 190 | return this; 191 | } 192 | } 193 | 194 | bool System.Collections.ICollection.IsSynchronized { 195 | get { 196 | return true; 197 | } 198 | } 199 | 200 | IEnumerator IEnumerable.GetEnumerator () 201 | { 202 | return GetEnumeratorInternal (); 203 | } 204 | 205 | public IEnumerator GetEnumerator () 206 | { 207 | return GetEnumeratorInternal (); 208 | } 209 | 210 | IEnumerator GetEnumeratorInternal () 211 | { 212 | foreach (var bag in container) 213 | foreach (T item in bag.Value.GetEnumerable ()) 214 | yield return item; 215 | } 216 | 217 | void System.Collections.ICollection.CopyTo (Array array, int index) 218 | { 219 | T[] a = array as T[]; 220 | if (a == null) 221 | return; 222 | 223 | CopyTo (a, index); 224 | } 225 | 226 | public void CopyTo (T[] array, int index) 227 | { 228 | int c = count; 229 | if (array.Length < c + index) 230 | throw new InvalidOperationException ("Array is not big enough"); 231 | 232 | CopyTo (array, index, c); 233 | } 234 | 235 | void CopyTo (T[] array, int index, int num) 236 | { 237 | int i = index; 238 | 239 | foreach (T item in this) { 240 | if (i >= num) 241 | break; 242 | 243 | array[i++] = item; 244 | } 245 | } 246 | 247 | public T[] ToArray () 248 | { 249 | int c = count; 250 | T[] temp = new T[c]; 251 | 252 | CopyTo (temp, 0, c); 253 | 254 | return temp; 255 | } 256 | 257 | int GetIndex () 258 | { 259 | return Thread.CurrentThread.ManagedThreadId; 260 | } 261 | 262 | CyclicDeque GetBag (out int index, bool createBag = true) 263 | { 264 | index = GetIndex (); 265 | CyclicDeque value; 266 | if (container.TryGetValue (index, out value)) 267 | return value; 268 | 269 | return createBag ? container.GetOrAdd (index, new CyclicDeque ()) : null; 270 | } 271 | 272 | void TidyBag (int index, CyclicDeque bag) 273 | { 274 | if (bag != null && bag.IsEmpty) { 275 | if (staging.TryRemove (index, out bag) && !bag.IsEmpty) 276 | staging.TryAdd (index, bag); 277 | } 278 | } 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /System.Collections.Concurrent/ConcurrentQueue.cs: -------------------------------------------------------------------------------- 1 | // ConcurrentQueue.cs 2 | // 3 | // Copyright (c) 2008 Jérémie "Garuma" Laval 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | // 23 | // 24 | 25 | using System; 26 | using System.Threading; 27 | using System.Collections; 28 | using System.Collections.Generic; 29 | 30 | namespace System.Collections.Concurrent 31 | { 32 | 33 | [System.Diagnostics.DebuggerDisplay ("Count={Count}")] 34 | [System.Diagnostics.DebuggerTypeProxy (typeof (CollectionDebuggerView<>))] 35 | public class ConcurrentQueue : IProducerConsumerCollection, IEnumerable, ICollection, 36 | IEnumerable 37 | { 38 | class Node 39 | { 40 | public T Value; 41 | public Node Next 42 | { 43 | get { return (Node)next; } 44 | } 45 | public object next; 46 | } 47 | 48 | object head = new Node (); 49 | Node Head { 50 | get { return (Node)head; } 51 | } 52 | 53 | object tail; 54 | Node Tail { 55 | get { return (Node)tail; } 56 | } 57 | 58 | int count; 59 | 60 | public ConcurrentQueue () 61 | { 62 | tail = head; 63 | } 64 | 65 | public ConcurrentQueue (IEnumerable collection): this() 66 | { 67 | foreach (T item in collection) 68 | Enqueue (item); 69 | } 70 | 71 | public void Enqueue (T item) 72 | { 73 | Node node = new Node (); 74 | node.Value = item; 75 | 76 | Node oldTail = null; 77 | Node oldNext = null; 78 | 79 | bool update = false; 80 | while (!update) { 81 | oldTail = Tail; 82 | oldNext = oldTail.Next; 83 | 84 | // Did tail was already updated ? 85 | if (tail == oldTail) { 86 | if (oldNext == null) { 87 | // The place is for us 88 | update = Interlocked.CompareExchange (ref Tail.next, node, null) == null; 89 | } else { 90 | // another Thread already used the place so give him a hand by putting tail where it should be 91 | Interlocked.CompareExchange (ref tail, oldNext, oldTail); 92 | } 93 | } 94 | } 95 | // At this point we added correctly our node, now we have to update tail. If it fails then it will be done by another thread 96 | Interlocked.CompareExchange (ref tail, node, oldTail); 97 | Interlocked.Increment (ref count); 98 | } 99 | 100 | bool IProducerConsumerCollection.TryAdd (T item) 101 | { 102 | Enqueue (item); 103 | return true; 104 | } 105 | 106 | public bool TryDequeue (out T result) 107 | { 108 | result = default (T); 109 | Node oldNext = null; 110 | bool advanced = false; 111 | 112 | while (!advanced) { 113 | Node oldHead = Head; 114 | Node oldTail = Tail; 115 | oldNext = oldHead.Next; 116 | 117 | if (oldHead == head) { 118 | // Empty case ? 119 | if (oldHead == oldTail) { 120 | // This should be false then 121 | if (oldNext != null) { 122 | // If not then the linked list is mal formed, update tail 123 | Interlocked.CompareExchange (ref tail, oldNext, oldTail); 124 | continue; 125 | } 126 | result = default (T); 127 | return false; 128 | } else { 129 | result = oldNext.Value; 130 | advanced = Interlocked.CompareExchange (ref head, oldNext, oldHead) == oldHead; 131 | } 132 | } 133 | } 134 | 135 | oldNext.Value = default (T); 136 | 137 | Interlocked.Decrement (ref count); 138 | 139 | return true; 140 | } 141 | 142 | public bool TryPeek (out T result) 143 | { 144 | result = default (T); 145 | bool update = true; 146 | 147 | while (update) 148 | { 149 | Node oldHead = Head; 150 | Node oldNext = oldHead.Next; 151 | 152 | if (oldNext == null) { 153 | result = default (T); 154 | return false; 155 | } 156 | 157 | result = oldNext.Value; 158 | 159 | //check if head has been updated 160 | update = head != oldHead; 161 | } 162 | return true; 163 | } 164 | 165 | internal void Clear () 166 | { 167 | count = 0; 168 | tail = head = new Node (); 169 | } 170 | 171 | IEnumerator IEnumerable.GetEnumerator () 172 | { 173 | return (IEnumerator)InternalGetEnumerator (); 174 | } 175 | 176 | public IEnumerator GetEnumerator () 177 | { 178 | return InternalGetEnumerator (); 179 | } 180 | 181 | IEnumerator InternalGetEnumerator () 182 | { 183 | Node my_head = Head; 184 | while ((my_head = my_head.Next) != null) { 185 | yield return my_head.Value; 186 | } 187 | } 188 | 189 | void ICollection.CopyTo (Array array, int index) 190 | { 191 | if (array == null) 192 | throw new ArgumentNullException ("array"); 193 | if (array.Rank > 1) 194 | throw new ArgumentException ("The array can't be multidimensional"); 195 | if (array.GetLowerBound (0) != 0) 196 | throw new ArgumentException ("The array needs to be 0-based"); 197 | 198 | T[] dest = array as T[]; 199 | if (dest == null) 200 | throw new ArgumentException ("The array cannot be cast to the collection element type", "array"); 201 | CopyTo (dest, index); 202 | } 203 | 204 | public void CopyTo (T[] array, int index) 205 | { 206 | if (array == null) 207 | throw new ArgumentNullException ("array"); 208 | if (index < 0) 209 | throw new ArgumentOutOfRangeException ("index"); 210 | if (index >= array.Length) 211 | throw new ArgumentException ("index is equals or greather than array length", "index"); 212 | 213 | IEnumerator e = InternalGetEnumerator (); 214 | int i = index; 215 | while (e.MoveNext ()) { 216 | if (i == array.Length - index) 217 | throw new ArgumentException ("The number of elememts in the collection exceeds the capacity of array", "array"); 218 | array[i++] = e.Current; 219 | } 220 | } 221 | 222 | public T[] ToArray () 223 | { 224 | return new List (this).ToArray (); 225 | } 226 | 227 | bool ICollection.IsSynchronized { 228 | get { return true; } 229 | } 230 | 231 | bool IProducerConsumerCollection.TryTake (out T item) 232 | { 233 | return TryDequeue (out item); 234 | } 235 | 236 | object syncRoot = new object(); 237 | object ICollection.SyncRoot { 238 | get { return syncRoot; } 239 | } 240 | 241 | public int Count { 242 | get { 243 | return count; 244 | } 245 | } 246 | 247 | public bool IsEmpty { 248 | get { 249 | return count == 0; 250 | } 251 | } 252 | } 253 | } 254 | -------------------------------------------------------------------------------- /System.Collections.Concurrent/ConcurrentStack.cs: -------------------------------------------------------------------------------- 1 | // ConcurrentStack.cs 2 | // 3 | // Authors: 4 | // Marek Safar 5 | // 6 | // Copyright (c) 2008 Jérémie "Garuma" Laval 7 | // Copyright (C) 2014 Xamarin Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | // 27 | // 28 | 29 | using System; 30 | using System.Threading; 31 | using System.Collections; 32 | using System.Collections.Generic; 33 | 34 | namespace System.Collections.Concurrent 35 | { 36 | 37 | [System.Diagnostics.DebuggerDisplay ("Count = {Count}")] 38 | [System.Diagnostics.DebuggerTypeProxy (typeof (CollectionDebuggerView<>))] 39 | public class ConcurrentStack : IProducerConsumerCollection, IEnumerable, 40 | ICollection, IEnumerable 41 | { 42 | class Node 43 | { 44 | public T Value = default (T); 45 | public Node Next; 46 | } 47 | 48 | object head; 49 | Node Head 50 | { 51 | get { return (Node)head; } 52 | } 53 | 54 | int count; 55 | 56 | public ConcurrentStack () 57 | { 58 | } 59 | 60 | public ConcurrentStack (IEnumerable collection) 61 | { 62 | if (collection == null) 63 | throw new ArgumentNullException ("collection"); 64 | 65 | foreach (T item in collection) 66 | Push (item); 67 | } 68 | 69 | bool IProducerConsumerCollection.TryAdd (T elem) 70 | { 71 | Push (elem); 72 | return true; 73 | } 74 | 75 | public void Push (T item) 76 | { 77 | Node temp = new Node (); 78 | temp.Value = item; 79 | do { 80 | temp.Next = Head; 81 | } while (Interlocked.CompareExchange (ref head, temp, temp.Next) != temp.Next); 82 | 83 | Interlocked.Increment (ref count); 84 | } 85 | 86 | public void PushRange (T[] items) 87 | { 88 | if (items == null) 89 | throw new ArgumentNullException ("items"); 90 | 91 | PushRange (items, 0, items.Length); 92 | } 93 | 94 | public void PushRange (T[] items, int startIndex, int count) 95 | { 96 | RangeArgumentsCheck (items, startIndex, count); 97 | 98 | Node insert = null; 99 | Node first = null; 100 | 101 | for (int i = startIndex; i < count; i++) { 102 | Node temp = new Node (); 103 | temp.Value = items[i]; 104 | temp.Next = insert; 105 | insert = temp; 106 | 107 | if (first == null) 108 | first = temp; 109 | } 110 | 111 | do { 112 | first.Next = Head; 113 | } while (Interlocked.CompareExchange (ref head, insert, first.Next) != first.Next); 114 | 115 | Interlocked.Add (ref this.count, count); 116 | } 117 | 118 | public bool TryPop (out T result) 119 | { 120 | Node temp; 121 | do { 122 | temp = Head; 123 | // The stak is empty 124 | if (temp == null) { 125 | result = default (T); 126 | return false; 127 | } 128 | } while (Interlocked.CompareExchange (ref head, temp.Next, temp) != temp); 129 | 130 | Interlocked.Decrement (ref count); 131 | 132 | result = temp.Value; 133 | 134 | return true; 135 | } 136 | 137 | public int TryPopRange (T[] items) 138 | { 139 | if (items == null) 140 | throw new ArgumentNullException ("items"); 141 | return TryPopRange (items, 0, items.Length); 142 | } 143 | 144 | public int TryPopRange (T[] items, int startIndex, int count) 145 | { 146 | RangeArgumentsCheck (items, startIndex, count); 147 | 148 | Node temp; 149 | Node end; 150 | 151 | do { 152 | temp = Head; 153 | if (temp == null) 154 | return 0; 155 | end = temp; 156 | for (int j = 0; j < count; j++) { 157 | end = end.Next; 158 | if (end == null) 159 | break; 160 | } 161 | } while (Interlocked.CompareExchange (ref head, end, temp) != temp); 162 | 163 | int i; 164 | for (i = startIndex; i < startIndex + count && temp != null; i++) { 165 | items[i] = temp.Value; 166 | end = temp; 167 | temp = temp.Next; 168 | } 169 | Interlocked.Add (ref this.count, -(i - startIndex)); 170 | 171 | return i - startIndex; 172 | } 173 | 174 | public bool TryPeek (out T result) 175 | { 176 | Node myHead = Head; 177 | if (myHead == null) { 178 | result = default (T); 179 | return false; 180 | } 181 | result = myHead.Value; 182 | return true; 183 | } 184 | 185 | public void Clear () 186 | { 187 | // This is not satisfactory 188 | count = 0; 189 | head = null; 190 | } 191 | 192 | IEnumerator IEnumerable.GetEnumerator () 193 | { 194 | return (IEnumerator)InternalGetEnumerator (); 195 | } 196 | 197 | public IEnumerator GetEnumerator () 198 | { 199 | return InternalGetEnumerator (); 200 | } 201 | 202 | IEnumerator InternalGetEnumerator () 203 | { 204 | Node my_head = Head; 205 | if (my_head == null) { 206 | yield break; 207 | } else { 208 | do { 209 | yield return my_head.Value; 210 | } while ((my_head = my_head.Next) != null); 211 | } 212 | } 213 | 214 | void ICollection.CopyTo (Array array, int index) 215 | { 216 | ICollection ic = new List (this); 217 | ic.CopyTo (array, index); 218 | } 219 | 220 | public void CopyTo (T[] array, int index) 221 | { 222 | if (array == null) 223 | throw new ArgumentNullException ("array"); 224 | if (index < 0) 225 | throw new ArgumentOutOfRangeException ("index"); 226 | if (index > array.Length) 227 | throw new ArgumentException ("index is equals or greather than array length", "index"); 228 | 229 | IEnumerator e = InternalGetEnumerator (); 230 | int i = index; 231 | while (e.MoveNext ()) { 232 | if (i == array.Length - index) 233 | throw new ArgumentException ("The number of elememts in the collection exceeds the capacity of array", "array"); 234 | array[i++] = e.Current; 235 | } 236 | } 237 | 238 | bool ICollection.IsSynchronized { 239 | get { return false; } 240 | } 241 | 242 | bool IProducerConsumerCollection.TryTake (out T item) 243 | { 244 | return TryPop (out item); 245 | } 246 | 247 | object ICollection.SyncRoot { 248 | get { 249 | throw new NotSupportedException (); 250 | } 251 | } 252 | 253 | public T[] ToArray () 254 | { 255 | return new List (this).ToArray (); 256 | } 257 | 258 | public int Count { 259 | get { 260 | return count; 261 | } 262 | } 263 | 264 | public bool IsEmpty { 265 | get { 266 | return count == 0; 267 | } 268 | } 269 | 270 | static void RangeArgumentsCheck (T[] items, int startIndex, int count) 271 | { 272 | if (items == null) 273 | throw new ArgumentNullException ("items"); 274 | if (startIndex < 0 || startIndex >= items.Length) 275 | throw new ArgumentOutOfRangeException ("startIndex"); 276 | if (count < 0) 277 | throw new ArgumentOutOfRangeException ("count"); 278 | if (startIndex + count > items.Length) 279 | throw new ArgumentException ("startIndex + count is greater than the length of items."); 280 | } 281 | } 282 | } 283 | -------------------------------------------------------------------------------- /System.Collections.Concurrent/IProducerConsumerCollection.cs: -------------------------------------------------------------------------------- 1 | // IConcurrentCollection.cs 2 | // 3 | // Copyright (c) 2008 Jérémie "Garuma" Laval 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | // 23 | // 24 | 25 | using System.Collections; 26 | using System.Collections.Generic; 27 | 28 | namespace System.Collections.Concurrent 29 | { 30 | public interface IProducerConsumerCollection : IEnumerable, ICollection, IEnumerable 31 | { 32 | bool TryAdd (T item); 33 | bool TryTake (out T item); 34 | T[] ToArray (); 35 | void CopyTo (T[] array, int index); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /System.Collections.Concurrent/OrderablePartitioner.cs: -------------------------------------------------------------------------------- 1 | // 2 | // OrderablePartitioner.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2009 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System; 28 | using System.Collections.Generic; 29 | 30 | namespace System.Collections.Concurrent 31 | { 32 | public abstract class OrderablePartitioner : Partitioner 33 | { 34 | bool keysOrderedInEachPartition; 35 | bool keysOrderedAcrossPartitions; 36 | bool keysNormalized; 37 | 38 | protected OrderablePartitioner (bool keysOrderedInEachPartition, 39 | bool keysOrderedAcrossPartitions, 40 | bool keysNormalized) : base () 41 | { 42 | this.keysOrderedInEachPartition = keysOrderedInEachPartition; 43 | this.keysOrderedAcrossPartitions = keysOrderedAcrossPartitions; 44 | this.keysNormalized = keysNormalized; 45 | } 46 | 47 | public override IEnumerable GetDynamicPartitions () 48 | { 49 | foreach (KeyValuePair item in GetOrderableDynamicPartitions ()) 50 | yield return item.Value; 51 | } 52 | 53 | public override IList> GetPartitions (int partitionCount) 54 | { 55 | IEnumerator[] temp = new IEnumerator[partitionCount]; 56 | IList>> enumerators 57 | = GetOrderablePartitions (partitionCount); 58 | 59 | for (int i = 0; i < enumerators.Count; i++) 60 | temp[i] = new ProxyEnumerator (enumerators[i]); 61 | 62 | return temp; 63 | } 64 | 65 | 66 | IEnumerator GetProxyEnumerator (IEnumerator> enumerator) 67 | { 68 | while (enumerator.MoveNext ()) 69 | yield return enumerator.Current.Value; 70 | } 71 | 72 | public abstract IList>> GetOrderablePartitions(int partitionCount); 73 | 74 | public virtual IEnumerable> GetOrderableDynamicPartitions() 75 | { 76 | if (!SupportsDynamicPartitions) 77 | throw new NotSupportedException (); 78 | 79 | return null; 80 | } 81 | 82 | public bool KeysOrderedInEachPartition { 83 | get { 84 | return keysOrderedInEachPartition; 85 | } 86 | } 87 | 88 | public bool KeysOrderedAcrossPartitions { 89 | get { 90 | return keysOrderedAcrossPartitions; 91 | } 92 | } 93 | 94 | public bool KeysNormalized { 95 | get { 96 | return keysNormalized; 97 | } 98 | } 99 | 100 | class ProxyEnumerator : IEnumerator, IDisposable 101 | { 102 | IEnumerator> internalEnumerator; 103 | 104 | internal ProxyEnumerator (IEnumerator> enumerator) 105 | { 106 | internalEnumerator = enumerator; 107 | } 108 | 109 | public void Dispose () 110 | { 111 | internalEnumerator.Dispose (); 112 | } 113 | 114 | public bool MoveNext () 115 | { 116 | if (!internalEnumerator.MoveNext ()) 117 | return false; 118 | 119 | Current = internalEnumerator.Current.Value; 120 | 121 | return true; 122 | } 123 | 124 | public void Reset () 125 | { 126 | internalEnumerator.Reset (); 127 | } 128 | 129 | object IEnumerator.Current { 130 | get { 131 | return Current; 132 | } 133 | } 134 | 135 | public TSource Current { 136 | get; 137 | private set; 138 | } 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /System.Collections.Concurrent/Partitioner.cs: -------------------------------------------------------------------------------- 1 | // 2 | // Partitioner.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2009 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System; 28 | using System.Collections.Generic; 29 | 30 | namespace System.Collections.Concurrent 31 | { 32 | using Partitioners; 33 | 34 | public static class Partitioner 35 | { 36 | public static OrderablePartitioner Create (IEnumerable source) 37 | { 38 | IList tempIList = source as IList; 39 | if (tempIList != null) 40 | return Create (tempIList, true); 41 | 42 | return new EnumerablePartitioner (source); 43 | } 44 | 45 | public static OrderablePartitioner Create (TSource[] array, bool loadBalance) 46 | { 47 | return Create (array, loadBalance); 48 | } 49 | 50 | public static OrderablePartitioner Create (IList list, bool loadBalance) 51 | { 52 | return new ListPartitioner (list); 53 | } 54 | 55 | public static OrderablePartitioner> Create (int fromInclusive, 56 | int toExclusive) 57 | { 58 | // This formula that is somewhat non-straighforward was guessed based on MS output 59 | int rangeSize = (toExclusive - fromInclusive) / (Environment.ProcessorCount * 3); 60 | if (rangeSize < 1) 61 | rangeSize = 1; 62 | 63 | return Create (fromInclusive, toExclusive, rangeSize); 64 | } 65 | 66 | public static OrderablePartitioner> Create (int fromInclusive, 67 | int toExclusive, 68 | int rangeSize) 69 | { 70 | if (fromInclusive >= toExclusive) 71 | throw new ArgumentOutOfRangeException ("toExclusive"); 72 | if (rangeSize <= 0) 73 | throw new ArgumentOutOfRangeException ("rangeSize"); 74 | 75 | return new UserRangePartitioner (fromInclusive, toExclusive, rangeSize); 76 | } 77 | 78 | public static OrderablePartitioner> Create (long fromInclusive, 79 | long toExclusive) 80 | { 81 | long rangeSize = (toExclusive - fromInclusive) / (Environment.ProcessorCount * 3); 82 | if (rangeSize < 1) 83 | rangeSize = 1; 84 | 85 | return Create (fromInclusive, toExclusive, rangeSize); 86 | } 87 | 88 | public static OrderablePartitioner> Create (long fromInclusive, 89 | long toExclusive, 90 | long rangeSize) 91 | { 92 | if (rangeSize <= 0) 93 | throw new ArgumentOutOfRangeException ("rangeSize"); 94 | if (fromInclusive >= toExclusive) 95 | throw new ArgumentOutOfRangeException ("toExclusive"); 96 | 97 | return new UserLongRangePartitioner (fromInclusive, toExclusive, rangeSize); 98 | } 99 | } 100 | 101 | public abstract class Partitioner 102 | { 103 | protected Partitioner () 104 | { 105 | 106 | } 107 | 108 | public virtual IEnumerable GetDynamicPartitions () 109 | { 110 | if (!SupportsDynamicPartitions) 111 | throw new NotSupportedException (); 112 | 113 | return null; 114 | } 115 | 116 | public abstract IList> GetPartitions (int partitionCount); 117 | 118 | public virtual bool SupportsDynamicPartitions { 119 | get { 120 | return false; 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /System.Collections.Generic/CollectionDebuggerView.cs: -------------------------------------------------------------------------------- 1 | // 2 | // CollectionDebuggerView.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2009 Novell, Inc (http://www.novell.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | using System.Diagnostics; 30 | 31 | namespace System.Collections.Generic 32 | { 33 | // 34 | // Custom debugger type proxy to display collections as arrays 35 | // 36 | internal sealed class CollectionDebuggerView 37 | { 38 | readonly ICollection c; 39 | 40 | public CollectionDebuggerView (ICollection col) 41 | { 42 | this.c = col; 43 | } 44 | 45 | [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] 46 | public T[] Items { 47 | get { 48 | var o = new T [c.Count]; 49 | c.CopyTo (o, 0); 50 | return o; 51 | } 52 | } 53 | } 54 | 55 | internal sealed class CollectionDebuggerView 56 | { 57 | readonly ICollection> c; 58 | 59 | public CollectionDebuggerView (ICollection> col) 60 | { 61 | this.c = col; 62 | } 63 | 64 | [DebuggerBrowsable (DebuggerBrowsableState.RootHidden)] 65 | public KeyValuePair[] Items { 66 | get { 67 | var o = new KeyValuePair [c.Count]; 68 | c.CopyTo (o, 0); 69 | return o; 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /System.Collections.Generic/DefaultEqualityComparer.cs: -------------------------------------------------------------------------------- 1 | // 2 | // DefaultEqualityComparer.cs 3 | // 4 | // Author: 5 | // Jim Borden 6 | // 7 | // Copyright (c) 2015 Couchbase, Inc All rights reserved. 8 | // 9 | // Licensed under the Apache License, Version 2.0 (the "License"); 10 | // you may not use this file except in compliance with the License. 11 | // You may obtain a copy of the License at 12 | // 13 | // http://www.apache.org/licenses/LICENSE-2.0 14 | // 15 | // Unless required by applicable law or agreed to in writing, software 16 | // distributed under the License is distributed on an "AS IS" BASIS, 17 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | // See the License for the specific language governing permissions and 19 | // limitations under the License. 20 | // 21 | using System; 22 | 23 | namespace System.Collections.Generic 24 | { 25 | //This class is needed for Unity iOS compatibility 26 | [Serializable] 27 | public sealed class DefaultComparer : IEqualityComparer, IEqualityComparer { 28 | 29 | public int GetHashCode (T obj) 30 | { 31 | if (obj == null) 32 | return 0; 33 | return obj.GetHashCode (); 34 | } 35 | 36 | public bool Equals (T x, T y) 37 | { 38 | if (x == null) 39 | return y == null; 40 | 41 | return x.Equals (y); 42 | } 43 | 44 | public int GetHashCode(object obj) 45 | { 46 | if (obj == null) 47 | return 0; 48 | 49 | if (!(obj is T)) 50 | throw new ArgumentException ("Argument is not compatible", "obj"); 51 | 52 | return GetHashCode ((T)obj); 53 | } 54 | 55 | public bool Equals(object x, object y) 56 | { 57 | 58 | if (x == null || y == null) { 59 | return false; 60 | } 61 | 62 | if (!(x is T) || !(y is T)) { 63 | return false; 64 | } 65 | 66 | return Equals((T)x, (T)y); 67 | } 68 | } 69 | } 70 | 71 | -------------------------------------------------------------------------------- /System.Collections.Generic/GenericEqualityComparer.cs: -------------------------------------------------------------------------------- 1 | // 2 | // GenericEqualityComparer.cs 3 | // 4 | // Author: 5 | // Jim Borden 6 | // 7 | // Copyright (c) 2015 Couchbase, Inc All rights reserved. 8 | // 9 | // Licensed under the Apache License, Version 2.0 (the "License"); 10 | // you may not use this file except in compliance with the License. 11 | // You may obtain a copy of the License at 12 | // 13 | // http://www.apache.org/licenses/LICENSE-2.0 14 | // 15 | // Unless required by applicable law or agreed to in writing, software 16 | // distributed under the License is distributed on an "AS IS" BASIS, 17 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | // See the License for the specific language governing permissions and 19 | // limitations under the License. 20 | // 21 | using System; 22 | using System.Collections.Generic; 23 | 24 | namespace System.Collections.Generic.Couchbase 25 | { 26 | //This class is needed for Unity iOS compatibility 27 | [Serializable] 28 | public sealed class GenericEqualityComparer : IEqualityComparer, IEqualityComparer where T : IEquatable { 29 | 30 | public int GetHashCode (T obj) 31 | { 32 | if (obj == null) 33 | return 0; 34 | 35 | return obj.GetHashCode (); 36 | } 37 | 38 | public bool Equals (T x, T y) 39 | { 40 | if (x == null) 41 | return y == null; 42 | 43 | return x.Equals (y); 44 | } 45 | 46 | public int GetHashCode(object obj) 47 | { 48 | if (obj == null) 49 | return 0; 50 | 51 | if (!(obj is T)) 52 | throw new ArgumentException ("Argument is not compatible", "obj"); 53 | 54 | return GetHashCode ((T)obj); 55 | } 56 | 57 | public bool Equals(object x, object y) 58 | { 59 | 60 | if(x == null || y == null) { 61 | return false; 62 | } 63 | 64 | if(!(x is T) || !(y is T)) { 65 | return false; 66 | } 67 | 68 | return Equals((T)x, (T)y); 69 | } 70 | } 71 | } 72 | 73 | -------------------------------------------------------------------------------- /System.Collections/IStructuralComparable.cs: -------------------------------------------------------------------------------- 1 | // 2 | // IStructuralComparable.cs 3 | // 4 | // Authors: 5 | // Zoltan Varga (vargaz@gmail.com) 6 | // 7 | // Copyright (C) 2009 Novell 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | namespace System.Collections 30 | { 31 | public interface IStructuralComparable { 32 | int CompareTo (object other, IComparer comparer); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /System.Collections/IStructuralEquatable.cs: -------------------------------------------------------------------------------- 1 | // 2 | // IStructuralEquatable.cs 3 | // 4 | // Authors: 5 | // Zoltan Varga (vargaz@gmail.com) 6 | // 7 | // Copyright (C) 2009 Novell 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | namespace System.Collections 30 | { 31 | public interface IStructuralEquatable { 32 | bool Equals (object other, IEqualityComparer comparer); 33 | 34 | int GetHashCode (IEqualityComparer comparer); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/AsyncStateMachineAttribute.cs: -------------------------------------------------------------------------------- 1 | // 2 | // AsyncStateMachineAttribute.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2012 Xamarin, Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | #if NET_4_5 30 | 31 | namespace System.Runtime.CompilerServices 32 | { 33 | [AttributeUsage (AttributeTargets.Method, Inherited = false)] 34 | [Serializable] 35 | public sealed class AsyncStateMachineAttribute : StateMachineAttribute 36 | { 37 | public AsyncStateMachineAttribute (Type stateMachineType) 38 | : base (stateMachineType) 39 | { 40 | } 41 | } 42 | } 43 | 44 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/AsyncTaskMethodBuilder.cs: -------------------------------------------------------------------------------- 1 | // 2 | // AsyncTaskMethodBuilder.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2011 Novell, Inc (http://www.novell.com) 8 | // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com) 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining 11 | // a copy of this software and associated documentation files (the 12 | // "Software"), to deal in the Software without restriction, including 13 | // without limitation the rights to use, copy, modify, merge, publish, 14 | // distribute, sublicense, and/or sell copies of the Software, and to 15 | // permit persons to whom the Software is furnished to do so, subject to 16 | // the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if NET_4_5 31 | 32 | using System.Threading; 33 | using System.Threading.Tasks; 34 | 35 | namespace System.Runtime.CompilerServices 36 | { 37 | public struct AsyncTaskMethodBuilder 38 | { 39 | readonly Task task; 40 | IAsyncStateMachine stateMachine; 41 | 42 | private AsyncTaskMethodBuilder (Task task) 43 | { 44 | this.task = task; 45 | this.stateMachine = null; 46 | } 47 | 48 | public Task Task { 49 | get { 50 | return task; 51 | } 52 | } 53 | 54 | public void AwaitOnCompleted (ref TAwaiter awaiter, ref TStateMachine stateMachine) 55 | where TAwaiter : INotifyCompletion 56 | where TStateMachine : IAsyncStateMachine 57 | { 58 | var action = new Action (stateMachine.MoveNext); 59 | awaiter.OnCompleted (action); 60 | } 61 | 62 | public void AwaitUnsafeOnCompleted (ref TAwaiter awaiter, ref TStateMachine stateMachine) 63 | where TAwaiter : ICriticalNotifyCompletion 64 | where TStateMachine : IAsyncStateMachine 65 | { 66 | var action = new Action (stateMachine.MoveNext); 67 | awaiter.UnsafeOnCompleted (action); 68 | } 69 | 70 | public static AsyncTaskMethodBuilder Create () 71 | { 72 | var task = new Task (TaskActionInvoker.Promise, null, CancellationToken.None, TaskCreationOptions.None, null); 73 | task.SetupScheduler (TaskScheduler.Current); 74 | return new AsyncTaskMethodBuilder (task); 75 | } 76 | 77 | public void SetException (Exception exception) 78 | { 79 | if (Task.TrySetException (new AggregateException (exception), exception is OperationCanceledException, true)) 80 | return; 81 | 82 | throw new InvalidOperationException ("The task has already completed"); 83 | } 84 | 85 | public void SetStateMachine (IAsyncStateMachine stateMachine) 86 | { 87 | if (stateMachine == null) 88 | throw new ArgumentNullException ("stateMachine"); 89 | 90 | if (this.stateMachine != null) 91 | throw new InvalidOperationException ("The state machine was previously set"); 92 | 93 | this.stateMachine = stateMachine; 94 | } 95 | 96 | public void SetResult () 97 | { 98 | if (!task.TrySetResult (null)) 99 | throw new InvalidOperationException ("The task has already completed"); 100 | } 101 | 102 | public void Start (ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine 103 | { 104 | if (stateMachine == null) 105 | throw new ArgumentNullException ("stateMachine"); 106 | 107 | stateMachine.MoveNext (); 108 | } 109 | } 110 | } 111 | 112 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/AsyncTaskMethodBuilder_T.cs: -------------------------------------------------------------------------------- 1 | // 2 | // AsyncTaskMethodBuilder_T.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2011 Novell, Inc (http://www.novell.com) 8 | // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com) 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining 11 | // a copy of this software and associated documentation files (the 12 | // "Software"), to deal in the Software without restriction, including 13 | // without limitation the rights to use, copy, modify, merge, publish, 14 | // distribute, sublicense, and/or sell copies of the Software, and to 15 | // permit persons to whom the Software is furnished to do so, subject to 16 | // the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if NET_4_5 31 | 32 | using System.Threading; 33 | using System.Threading.Tasks; 34 | 35 | namespace System.Runtime.CompilerServices 36 | { 37 | public struct AsyncTaskMethodBuilder 38 | { 39 | readonly Task task; 40 | IAsyncStateMachine stateMachine; 41 | 42 | private AsyncTaskMethodBuilder (Task task) 43 | { 44 | this.task = task; 45 | this.stateMachine = null; 46 | } 47 | 48 | public Task Task { 49 | get { 50 | return task; 51 | } 52 | } 53 | 54 | public void AwaitOnCompleted (ref TAwaiter awaiter, ref TStateMachine stateMachine) 55 | where TAwaiter : INotifyCompletion 56 | where TStateMachine : IAsyncStateMachine 57 | { 58 | var action = new Action (stateMachine.MoveNext); 59 | awaiter.OnCompleted (action); 60 | } 61 | 62 | public void AwaitUnsafeOnCompleted (ref TAwaiter awaiter, ref TStateMachine stateMachine) 63 | where TAwaiter : ICriticalNotifyCompletion 64 | where TStateMachine : IAsyncStateMachine 65 | { 66 | var action = new Action (stateMachine.MoveNext); 67 | awaiter.UnsafeOnCompleted (action); 68 | } 69 | 70 | public static AsyncTaskMethodBuilder Create () 71 | { 72 | var task = new Task (TaskActionInvoker.Promise, null, CancellationToken.None, TaskCreationOptions.None, null); 73 | task.SetupScheduler (TaskScheduler.Current); 74 | return new AsyncTaskMethodBuilder (task); 75 | } 76 | 77 | public void SetException (Exception exception) 78 | { 79 | if (Task.TrySetException (new AggregateException (exception), exception is OperationCanceledException, true)) 80 | return; 81 | 82 | throw new InvalidOperationException ("The task has already completed"); 83 | } 84 | 85 | public void SetStateMachine (IAsyncStateMachine stateMachine) 86 | { 87 | if (stateMachine == null) 88 | throw new ArgumentNullException ("stateMachine"); 89 | 90 | if (this.stateMachine != null) 91 | throw new InvalidOperationException ("The state machine was previously set"); 92 | 93 | this.stateMachine = stateMachine; 94 | } 95 | 96 | public void SetResult (TResult result) 97 | { 98 | if (!task.TrySetResult (result)) 99 | throw new InvalidOperationException ("The task has already completed"); 100 | } 101 | 102 | public void Start (ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine 103 | { 104 | if (stateMachine == null) 105 | throw new ArgumentNullException ("stateMachine"); 106 | 107 | stateMachine.MoveNext (); 108 | } 109 | } 110 | } 111 | 112 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/AsyncVoidMethodBuilder.cs: -------------------------------------------------------------------------------- 1 | // 2 | // AsyncVoidMethodBuilder.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2011 Novell, Inc (http://www.novell.com) 8 | // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com) 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining 11 | // a copy of this software and associated documentation files (the 12 | // "Software"), to deal in the Software without restriction, including 13 | // without limitation the rights to use, copy, modify, merge, publish, 14 | // distribute, sublicense, and/or sell copies of the Software, and to 15 | // permit persons to whom the Software is furnished to do so, subject to 16 | // the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if NET_4_5 31 | 32 | using System.Threading; 33 | 34 | namespace System.Runtime.CompilerServices 35 | { 36 | public struct AsyncVoidMethodBuilder 37 | { 38 | static readonly SynchronizationContext null_context = new SynchronizationContext (); 39 | 40 | readonly SynchronizationContext context; 41 | IAsyncStateMachine stateMachine; 42 | 43 | private AsyncVoidMethodBuilder (SynchronizationContext context) 44 | { 45 | this.context = context; 46 | this.stateMachine = null; 47 | } 48 | 49 | public void AwaitOnCompleted (ref TAwaiter awaiter, ref TStateMachine stateMachine) 50 | where TAwaiter : INotifyCompletion 51 | where TStateMachine : IAsyncStateMachine 52 | { 53 | var action = new Action (stateMachine.MoveNext); 54 | awaiter.OnCompleted (action); 55 | } 56 | 57 | public void AwaitUnsafeOnCompleted (ref TAwaiter awaiter, ref TStateMachine stateMachine) 58 | where TAwaiter : ICriticalNotifyCompletion 59 | where TStateMachine : IAsyncStateMachine 60 | { 61 | var action = new Action (stateMachine.MoveNext); 62 | awaiter.UnsafeOnCompleted (action); 63 | } 64 | 65 | public static AsyncVoidMethodBuilder Create () 66 | { 67 | var ctx = SynchronizationContext.Current ?? null_context; 68 | ctx.OperationStarted (); 69 | 70 | return new AsyncVoidMethodBuilder (ctx); 71 | } 72 | 73 | public void SetException (Exception exception) 74 | { 75 | if (exception == null) 76 | throw new ArgumentNullException ("exception"); 77 | 78 | try { 79 | context.Post (l => { throw (Exception) l; }, exception); 80 | } finally { 81 | SetResult (); 82 | } 83 | } 84 | 85 | public void SetStateMachine (IAsyncStateMachine stateMachine) 86 | { 87 | if (stateMachine == null) 88 | throw new ArgumentNullException ("stateMachine"); 89 | 90 | if (this.stateMachine != null) 91 | throw new InvalidOperationException ("The state machine was previously set"); 92 | 93 | this.stateMachine = stateMachine; 94 | } 95 | 96 | public void SetResult () 97 | { 98 | context.OperationCompleted (); 99 | } 100 | 101 | public void Start (ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine 102 | { 103 | if (stateMachine == null) 104 | throw new ArgumentNullException ("stateMachine"); 105 | 106 | stateMachine.MoveNext (); 107 | } 108 | } 109 | } 110 | 111 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/ConfiguredTaskAwaitable.cs: -------------------------------------------------------------------------------- 1 | // 2 | // ConfiguredTaskAwaitable.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | #if NET_4_5 30 | 31 | using System.Threading; 32 | using System.Threading.Tasks; 33 | using System.Runtime.ExceptionServices; 34 | 35 | namespace System.Runtime.CompilerServices 36 | { 37 | public struct ConfiguredTaskAwaitable 38 | { 39 | public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion 40 | { 41 | readonly Task task; 42 | readonly bool continueOnSourceContext; 43 | 44 | internal ConfiguredTaskAwaiter (Task task, bool continueOnSourceContext) 45 | { 46 | this.task = task; 47 | this.continueOnSourceContext = continueOnSourceContext; 48 | } 49 | 50 | public bool IsCompleted { 51 | get { 52 | return task.IsCompleted; 53 | } 54 | } 55 | 56 | public void GetResult () 57 | { 58 | if (!task.IsCompleted) 59 | task.WaitCore (Timeout.Infinite, CancellationToken.None, true); 60 | 61 | if (task.Status != TaskStatus.RanToCompletion) 62 | ExceptionDispatchInfo.Capture (TaskAwaiter.HandleUnexpectedTaskResult (task)).Throw (); 63 | } 64 | 65 | public void OnCompleted (Action continuation) 66 | { 67 | if (continuation == null) 68 | throw new ArgumentNullException ("continuation"); 69 | 70 | TaskAwaiter.HandleOnCompleted (task, continuation, continueOnSourceContext, true); 71 | } 72 | 73 | public void UnsafeOnCompleted (Action continuation) 74 | { 75 | if (continuation == null) 76 | throw new ArgumentNullException ("continuation"); 77 | 78 | TaskAwaiter.HandleOnCompleted (task, continuation, continueOnSourceContext, false); 79 | } 80 | } 81 | 82 | readonly ConfiguredTaskAwaiter awaiter; 83 | 84 | internal ConfiguredTaskAwaitable (Task task, bool continueOnSourceContext) 85 | { 86 | awaiter = new ConfiguredTaskAwaiter (task, continueOnSourceContext); 87 | } 88 | 89 | public ConfiguredTaskAwaiter GetAwaiter() 90 | { 91 | return awaiter; 92 | } 93 | } 94 | } 95 | 96 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/ConfiguredTaskAwaitable_T.cs: -------------------------------------------------------------------------------- 1 | // 2 | // ConfiguredTaskAwaitable_T.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | #if NET_4_5 30 | 31 | using System.Threading; 32 | using System.Threading.Tasks; 33 | using System.Runtime.ExceptionServices; 34 | 35 | namespace System.Runtime.CompilerServices 36 | { 37 | public struct ConfiguredTaskAwaitable 38 | { 39 | public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion 40 | { 41 | readonly Task task; 42 | readonly bool continueOnSourceContext; 43 | 44 | internal ConfiguredTaskAwaiter (Task task, bool continueOnSourceContext) 45 | { 46 | this.task = task; 47 | this.continueOnSourceContext = continueOnSourceContext; 48 | } 49 | 50 | public bool IsCompleted { 51 | get { 52 | return task.IsCompleted; 53 | } 54 | } 55 | 56 | public TResult GetResult () 57 | { 58 | if (!task.IsCompleted) 59 | task.WaitCore (Timeout.Infinite, CancellationToken.None, true); 60 | 61 | if (task.Status != TaskStatus.RanToCompletion) 62 | ExceptionDispatchInfo.Capture (TaskAwaiter.HandleUnexpectedTaskResult (task)).Throw (); 63 | 64 | return task.Result; 65 | } 66 | 67 | public void OnCompleted (Action continuation) 68 | { 69 | if (continuation == null) 70 | throw new ArgumentNullException ("continuation"); 71 | 72 | TaskAwaiter.HandleOnCompleted (task, continuation, continueOnSourceContext, true); 73 | } 74 | 75 | public void UnsafeOnCompleted (Action continuation) 76 | { 77 | if (continuation == null) 78 | throw new ArgumentNullException ("continuation"); 79 | 80 | TaskAwaiter.HandleOnCompleted (task, continuation, continueOnSourceContext, false); 81 | } 82 | } 83 | 84 | readonly ConfiguredTaskAwaiter awaiter; 85 | 86 | internal ConfiguredTaskAwaitable (Task task, bool continueOnSourceContext) 87 | { 88 | awaiter = new ConfiguredTaskAwaiter (task, continueOnSourceContext); 89 | } 90 | 91 | public ConfiguredTaskAwaiter GetAwaiter() 92 | { 93 | return awaiter; 94 | } 95 | } 96 | } 97 | 98 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/IAsyncStateMachine.cs: -------------------------------------------------------------------------------- 1 | // 2 | // IAsyncStateMachine.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2012 Xamarin, Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | #if NET_4_5 30 | 31 | namespace System.Runtime.CompilerServices 32 | { 33 | public interface IAsyncStateMachine 34 | { 35 | void MoveNext (); 36 | void SetStateMachine (IAsyncStateMachine stateMachine); 37 | } 38 | } 39 | 40 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/ICriticalNotifyCompletion.cs: -------------------------------------------------------------------------------- 1 | // 2 | // ICriticalNotifyCompletion.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2012 Xamarin, Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | #if NET_4_5 30 | 31 | namespace System.Runtime.CompilerServices 32 | { 33 | public interface ICriticalNotifyCompletion : INotifyCompletion 34 | { 35 | void UnsafeOnCompleted (Action continuation); 36 | } 37 | } 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/INotifyCompletion.cs: -------------------------------------------------------------------------------- 1 | // 2 | // INotifyCompletion.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2012 Xamarin, Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | #if NET_4_5 30 | 31 | namespace System.Runtime.CompilerServices 32 | { 33 | public interface INotifyCompletion 34 | { 35 | void OnCompleted (Action continuation); 36 | } 37 | } 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/StateMachineAttribute.cs: -------------------------------------------------------------------------------- 1 | // 2 | // StateMachineAttribute.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2012 Xamarin, Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | #if NET_4_5 30 | 31 | namespace System.Runtime.CompilerServices 32 | { 33 | [AttributeUsage (AttributeTargets.Method, Inherited = false)] 34 | [Serializable] 35 | public class StateMachineAttribute : Attribute 36 | { 37 | public StateMachineAttribute (Type stateMachineType) 38 | { 39 | StateMachineType = stateMachineType; 40 | } 41 | 42 | public Type StateMachineType { get; private set; } 43 | } 44 | } 45 | 46 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/TaskAwaiter.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskAwaiter.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2011 Novell, Inc (http://www.novell.com) 8 | // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com) 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining 11 | // a copy of this software and associated documentation files (the 12 | // "Software"), to deal in the Software without restriction, including 13 | // without limitation the rights to use, copy, modify, merge, publish, 14 | // distribute, sublicense, and/or sell copies of the Software, and to 15 | // permit persons to whom the Software is furnished to do so, subject to 16 | // the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if NET_4_5 31 | 32 | using System.Threading; 33 | using System.Threading.Tasks; 34 | using System.Runtime.ExceptionServices; 35 | 36 | namespace System.Runtime.CompilerServices 37 | { 38 | public struct TaskAwaiter : ICriticalNotifyCompletion 39 | { 40 | readonly Task task; 41 | 42 | internal TaskAwaiter (Task task) 43 | { 44 | this.task = task; 45 | } 46 | 47 | public bool IsCompleted { 48 | get { 49 | return task.IsCompleted; 50 | } 51 | } 52 | 53 | public void GetResult () 54 | { 55 | if (!task.IsCompleted) 56 | task.WaitCore (Timeout.Infinite, CancellationToken.None, true); 57 | 58 | if (task.Status != TaskStatus.RanToCompletion) 59 | // Merge current and dispatched stack traces if there is any 60 | ExceptionDispatchInfo.Capture (HandleUnexpectedTaskResult (task)).Throw (); 61 | } 62 | 63 | internal static Exception HandleUnexpectedTaskResult (Task task) 64 | { 65 | var slot = task.ExceptionSlot; 66 | switch (task.Status) { 67 | case TaskStatus.Canceled: 68 | // Use original exception when we have one 69 | if (slot.Exception != null) 70 | goto case TaskStatus.Faulted; 71 | 72 | return new TaskCanceledException (task); 73 | case TaskStatus.Faulted: 74 | // Mark the exception as observed when GetResult throws 75 | slot.Observed = true; 76 | return slot.Exception.InnerException; 77 | default: 78 | throw new ArgumentException (string.Format ("Unexpected task `{0}' status `{1}'", task.Id, task.Status)); 79 | } 80 | } 81 | 82 | internal static void HandleOnCompleted (Task task, Action continuation, bool continueOnSourceContext, bool manageContext) 83 | { 84 | if (continueOnSourceContext && SynchronizationContext.Current != null && SynchronizationContext.Current.GetType () != typeof (SynchronizationContext)) { 85 | task.ContinueWith (new SynchronizationContextContinuation (continuation, SynchronizationContext.Current)); 86 | } else { 87 | IContinuation cont; 88 | Task cont_task; 89 | if (continueOnSourceContext && !TaskScheduler.IsDefault) { 90 | cont_task = new Task (TaskActionInvoker.Create (continuation), null, CancellationToken.None, TaskCreationOptions.None, null); 91 | cont_task.SetupScheduler (TaskScheduler.Current); 92 | cont = new SchedulerAwaitContinuation (cont_task); 93 | } else { 94 | cont_task = null; 95 | cont = new AwaiterActionContinuation (continuation); 96 | } 97 | 98 | // 99 | // This is awaiter continuation. For finished tasks we get false result and need to 100 | // queue the continuation otherwise the task would block 101 | // 102 | if (task.ContinueWith (cont, false)) 103 | return; 104 | 105 | if (cont_task == null) { 106 | cont_task = new Task (TaskActionInvoker.Create (continuation), null, CancellationToken.None, TaskCreationOptions.None, null); 107 | cont_task.SetupScheduler (TaskScheduler.Current); 108 | } 109 | 110 | cont_task.Schedule (true); 111 | } 112 | } 113 | 114 | public void OnCompleted (Action continuation) 115 | { 116 | if (continuation == null) 117 | throw new ArgumentNullException ("continuation"); 118 | 119 | HandleOnCompleted (task, continuation, true, true); 120 | } 121 | 122 | public void UnsafeOnCompleted (Action continuation) 123 | { 124 | if (continuation == null) 125 | throw new ArgumentNullException ("continuation"); 126 | 127 | HandleOnCompleted (task, continuation, true, false); 128 | } 129 | } 130 | } 131 | 132 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/TaskAwaiter_T.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskAwaiter_T.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2011 Novell, Inc (http://www.novell.com) 8 | // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com) 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining 11 | // a copy of this software and associated documentation files (the 12 | // "Software"), to deal in the Software without restriction, including 13 | // without limitation the rights to use, copy, modify, merge, publish, 14 | // distribute, sublicense, and/or sell copies of the Software, and to 15 | // permit persons to whom the Software is furnished to do so, subject to 16 | // the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if NET_4_5 31 | 32 | using System.Threading; 33 | using System.Threading.Tasks; 34 | using System.Runtime.ExceptionServices; 35 | 36 | namespace System.Runtime.CompilerServices 37 | { 38 | public struct TaskAwaiter : ICriticalNotifyCompletion 39 | { 40 | readonly Task task; 41 | 42 | internal TaskAwaiter (Task task) 43 | { 44 | this.task = task; 45 | } 46 | 47 | public bool IsCompleted { 48 | get { 49 | return task.IsCompleted; 50 | } 51 | } 52 | 53 | public TResult GetResult () 54 | { 55 | if (!task.IsCompleted) 56 | task.WaitCore (Timeout.Infinite, CancellationToken.None, true); 57 | 58 | if (task.Status != TaskStatus.RanToCompletion) 59 | ExceptionDispatchInfo.Capture (TaskAwaiter.HandleUnexpectedTaskResult (task)).Throw (); 60 | 61 | return task.Result; 62 | } 63 | 64 | public void OnCompleted (Action continuation) 65 | { 66 | if (continuation == null) 67 | throw new ArgumentNullException ("continuation"); 68 | 69 | TaskAwaiter.HandleOnCompleted (task, continuation, true, true); 70 | } 71 | 72 | public void UnsafeOnCompleted (Action continuation) 73 | { 74 | if (continuation == null) 75 | throw new ArgumentNullException ("continuation"); 76 | 77 | TaskAwaiter.HandleOnCompleted (task, continuation, true, false); 78 | } 79 | } 80 | } 81 | 82 | #endif -------------------------------------------------------------------------------- /System.Runtime.CompilerServices/YieldAwaitable.cs: -------------------------------------------------------------------------------- 1 | // 2 | // YieldAwaitable.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright (C) 2011 Novell, Inc (http://www.novell.com) 8 | // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com) 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining 11 | // a copy of this software and associated documentation files (the 12 | // "Software"), to deal in the Software without restriction, including 13 | // without limitation the rights to use, copy, modify, merge, publish, 14 | // distribute, sublicense, and/or sell copies of the Software, and to 15 | // permit persons to whom the Software is furnished to do so, subject to 16 | // the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,) 22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if NET_4_5 31 | 32 | using System.Threading; 33 | using System.Threading.Tasks; 34 | 35 | namespace System.Runtime.CompilerServices 36 | { 37 | public struct YieldAwaitable 38 | { 39 | public struct YieldAwaiter : ICriticalNotifyCompletion 40 | { 41 | public bool IsCompleted { 42 | get { 43 | return false; 44 | } 45 | } 46 | 47 | public void OnCompleted (Action continuation) 48 | { 49 | OnCompleted (continuation, false); 50 | } 51 | 52 | public void UnsafeOnCompleted (Action continuation) 53 | { 54 | OnCompleted (continuation, true); 55 | } 56 | 57 | void OnCompleted (Action continuation, bool isUnsafe) 58 | { 59 | if (continuation == null) 60 | throw new ArgumentNullException ("continuation"); 61 | 62 | var ctx = SynchronizationContext.Current; 63 | if (ctx != null && ctx.GetType () != typeof (SynchronizationContext)) { 64 | ctx.Post (l => ((Action) l) (), continuation); 65 | return; 66 | } 67 | 68 | if (TaskScheduler.IsDefault) { 69 | // 70 | // Pass continuation as an argument to avoid allocating 71 | // hoisting class 72 | // 73 | WaitCallback callBack = l => ((Action) l) (); 74 | //if (isUnsafe) { 75 | // ThreadPool.UnsafeQueueUserWorkItem (callBack, continuation); 76 | //} else { 77 | ThreadPool.QueueUserWorkItem (callBack, continuation); 78 | //} 79 | return; 80 | } 81 | 82 | new Task (continuation).Start (TaskScheduler.Current); 83 | } 84 | 85 | public void GetResult () 86 | { 87 | } 88 | } 89 | 90 | public YieldAwaitable.YieldAwaiter GetAwaiter () 91 | { 92 | return new YieldAwaiter (); 93 | } 94 | } 95 | } 96 | 97 | #endif -------------------------------------------------------------------------------- /System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs: -------------------------------------------------------------------------------- 1 | // 2 | // ExceptionDispatchInfo.cs 3 | // 4 | // Authors: 5 | // Marek Safar (marek.safar@gmail.com) 6 | // 7 | // Copyright 2011 Xamarin, Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | #if NET_4_5 30 | 31 | namespace System.Runtime.ExceptionServices 32 | { 33 | public sealed class ExceptionDispatchInfo 34 | { 35 | readonly Exception exception; 36 | 37 | private ExceptionDispatchInfo (Exception source) 38 | { 39 | this.exception = source; 40 | } 41 | 42 | public Exception SourceException { 43 | get { 44 | return exception; 45 | } 46 | } 47 | 48 | public static ExceptionDispatchInfo Capture (Exception source) 49 | { 50 | if (source == null) 51 | throw new ArgumentNullException ("source"); 52 | 53 | return new ExceptionDispatchInfo (source); 54 | } 55 | 56 | public void Throw () 57 | { 58 | //exception.CaptureTrace (); 59 | 60 | throw exception; 61 | } 62 | } 63 | } 64 | 65 | #endif -------------------------------------------------------------------------------- /System.Runtime.Remoting.Messaging/AsyncResult.cs: -------------------------------------------------------------------------------- 1 | // 2 | // System.Runtime.Remoting.Messaging/AsyncResult.cs 3 | // 4 | // Authors: 5 | // Joe Shaw (joe@ximian.com) 6 | // Martin Baulig (martin@gnome.org) 7 | // Dietmar Maurer (dietmar@ximian.com) 8 | // Duncan Mak (duncan@ximian.com) 9 | // 10 | // (C) 2001 Ximian, Inc. http://www.ximian.com 11 | // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) 12 | // 13 | // Permission is hereby granted, free of charge, to any person obtaining 14 | // a copy of this software and associated documentation files (the 15 | // "Software"), to deal in the Software without restriction, including 16 | // without limitation the rights to use, copy, modify, merge, publish, 17 | // distribute, sublicense, and/or sell copies of the Software, and to 18 | // permit persons to whom the Software is furnished to do so, subject to 19 | // the following conditions: 20 | // 21 | // The above copyright notice and this permission notice shall be 22 | // included in all copies or substantial portions of the Software. 23 | // 24 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 25 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 26 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 27 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 28 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 29 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 30 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 31 | // 32 | 33 | using System; 34 | using System.Threading; 35 | using System.Runtime.CompilerServices; 36 | using System.Runtime.InteropServices; 37 | 38 | namespace System.Runtime.Remoting.Messaging { 39 | 40 | [System.Runtime.InteropServices.ComVisible (true)] 41 | [StructLayout (LayoutKind.Sequential)] 42 | internal class AsyncResult : IAsyncResult, IMessageSink { 43 | 44 | #pragma warning disable 169, 414, 649 45 | object async_state; 46 | WaitHandle handle; 47 | object async_delegate; 48 | IntPtr data; 49 | object object_data; 50 | bool sync_completed; 51 | bool completed; 52 | bool endinvoke_called; 53 | object async_callback; 54 | ExecutionContext current; 55 | ExecutionContext original; 56 | long add_time; 57 | #pragma warning restore 169, 414, 649 58 | 59 | // not part of MonoAsyncResult... 60 | //MonoMethodMessage call_message; 61 | #pragma warning disable 0414 62 | IMessageCtrl message_ctrl; 63 | #pragma warning restore 64 | IMessage reply_message; 65 | 66 | internal AsyncResult () 67 | { 68 | } 69 | 70 | internal AsyncResult (WaitCallback cb, object state, bool capture_context) 71 | { 72 | async_state = state; 73 | async_delegate = cb; 74 | if (capture_context) 75 | current = ExecutionContext.Capture (); 76 | } 77 | 78 | public virtual object AsyncState 79 | { 80 | get { 81 | return async_state; 82 | } 83 | } 84 | 85 | public virtual WaitHandle AsyncWaitHandle { 86 | get { 87 | lock (this) { 88 | if (handle == null) 89 | handle = new ManualResetEvent (completed); 90 | 91 | return handle; 92 | } 93 | } 94 | } 95 | 96 | public virtual bool CompletedSynchronously 97 | { 98 | get { 99 | return sync_completed; 100 | } 101 | } 102 | 103 | public virtual bool IsCompleted 104 | { 105 | get { 106 | return completed; 107 | } 108 | } 109 | 110 | public bool EndInvokeCalled 111 | { 112 | get { 113 | return endinvoke_called; 114 | } 115 | set { 116 | endinvoke_called = value; 117 | } 118 | } 119 | 120 | public virtual object AsyncDelegate 121 | { 122 | get { 123 | return async_delegate; 124 | } 125 | } 126 | 127 | public IMessageSink NextSink { 128 | get { 129 | return null; 130 | } 131 | } 132 | 133 | public virtual IMessageCtrl AsyncProcessMessage (IMessage msg, IMessageSink replySink) 134 | { 135 | // Never called 136 | throw new NotSupportedException (); 137 | } 138 | 139 | public virtual IMessage GetReplyMessage() 140 | { 141 | return reply_message; 142 | } 143 | 144 | public virtual void SetMessageCtrl (IMessageCtrl mc) 145 | { 146 | message_ctrl = mc; 147 | } 148 | 149 | internal void SetCompletedSynchronously (bool completed) 150 | { 151 | sync_completed = completed; 152 | } 153 | 154 | internal IMessage EndInvoke () 155 | { 156 | lock (this) { 157 | if (completed) 158 | return reply_message; 159 | } 160 | 161 | AsyncWaitHandle.WaitOne (); 162 | return reply_message; 163 | } 164 | 165 | public virtual IMessage SyncProcessMessage (IMessage msg) 166 | { 167 | reply_message = msg; 168 | 169 | lock (this) { 170 | completed = true; 171 | if (handle != null) 172 | ((ManualResetEvent) AsyncWaitHandle).Set (); 173 | } 174 | 175 | if (async_callback != null) { 176 | AsyncCallback ac = (AsyncCallback) async_callback; 177 | ac (this); 178 | } 179 | 180 | return null; 181 | } 182 | 183 | /*internal MonoMethodMessage CallMessage 184 | { 185 | get { return call_message; } 186 | set { call_message = value; } 187 | }*/ 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /System.Threading.Tasks.Net35.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {DCB5D745-525C-46A1-BFC0-E12F87AB6165} 7 | Library 8 | System.Threading.Tasks.Net35 9 | System.Threading.Tasks.Net35 10 | v3.5 11 | 1.1 12 | False 13 | 14 | 15 | True 16 | full 17 | False 18 | bin\Debug 19 | DEBUG;TRACE;NET_4_5; 20 | prompt 21 | 4 22 | False 23 | True 24 | 25 | 26 | True 27 | bin\Release 28 | prompt 29 | 4 30 | False 31 | True 32 | NET_4_5; 33 | pdbonly 34 | true 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /System.Threading.Tasks.Unity.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {DCB5D745-525C-46A1-BFC0-E12F87AB6165} 7 | Library 8 | System.Threading.Tasks.Net35 9 | System.Threading.Tasks.Net35 10 | v3.5 11 | 1.1 12 | False 13 | 14 | 15 | True 16 | full 17 | False 18 | bin\Debug 19 | DEBUG;TRACE;NET_4_5;UNITY 20 | prompt 21 | 4 22 | False 23 | True 24 | 25 | 26 | True 27 | bin\Release 28 | prompt 29 | 4 30 | False 31 | True 32 | NET_4_5;UNITY 33 | pdbonly 34 | true 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /System.Threading.Tasks/CyclicDeque.cs: -------------------------------------------------------------------------------- 1 | // 2 | // CyclicDeque.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2009 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System; 28 | using System.Collections.Generic; 29 | using System.Threading; 30 | 31 | namespace System.Threading.Tasks 32 | { 33 | class CyclicDeque : IConcurrentDeque 34 | { 35 | const int BaseSize = 11; 36 | 37 | int bottom; 38 | int top; 39 | int upperBound; 40 | CircularArray array = new CircularArray (BaseSize); 41 | 42 | public void PushBottom (T obj) 43 | { 44 | int b = bottom; 45 | var a = array; 46 | 47 | // Take care of growing 48 | var size = b - top - upperBound; 49 | if (size > a.Size) { 50 | upperBound = top; 51 | a = a.Grow (b, upperBound); 52 | array = a; 53 | } 54 | 55 | // Register the new value 56 | a.segment[b % a.size] = obj; 57 | Interlocked.Increment (ref bottom); 58 | } 59 | 60 | public PopResult PopBottom (out T obj) 61 | { 62 | obj = default (T); 63 | 64 | int b = Interlocked.Decrement (ref bottom); 65 | var a = array; 66 | int t = top; 67 | int size = b - t; 68 | 69 | if (size < 0) { 70 | // Set bottom to t 71 | Interlocked.Add (ref bottom, t - b); 72 | return PopResult.Empty; 73 | } 74 | 75 | obj = a.segment[b % a.size]; 76 | if (size > 0) 77 | return PopResult.Succeed; 78 | Interlocked.Add (ref bottom, t + 1 - b); 79 | 80 | if (Interlocked.CompareExchange (ref top, t + 1, t) != t) 81 | return PopResult.Empty; 82 | 83 | return PopResult.Succeed; 84 | } 85 | 86 | public bool PeekBottom (out T obj) 87 | { 88 | obj = default (T); 89 | 90 | int b = Interlocked.Decrement (ref bottom); 91 | var a = array; 92 | int t = top; 93 | int size = b - t; 94 | 95 | if (size < 0) 96 | return false; 97 | 98 | obj = a.segment[b % a.size]; 99 | return true; 100 | } 101 | 102 | public PopResult PopTop (out T obj) 103 | { 104 | obj = default (T); 105 | 106 | int t = top; 107 | int b = bottom; 108 | 109 | if (b - t <= 0) 110 | return PopResult.Empty; 111 | 112 | if (Interlocked.CompareExchange (ref top, t + 1, t) != t) 113 | return PopResult.Abort; 114 | 115 | var a = array; 116 | obj = a.segment[t % a.size]; 117 | 118 | return PopResult.Succeed; 119 | } 120 | 121 | internal bool PeekTop (out T obj) 122 | { 123 | obj = default (T); 124 | 125 | int t = top; 126 | int b = bottom; 127 | 128 | if (b - t <= 0) 129 | return false; 130 | 131 | var a = array; 132 | obj = a.segment[t % a.size]; 133 | 134 | return true; 135 | } 136 | 137 | public IEnumerable GetEnumerable () 138 | { 139 | var a = array; 140 | return a.GetEnumerable (bottom, ref top); 141 | } 142 | 143 | public bool IsEmpty { 144 | get { 145 | int t = top; 146 | int b = bottom; 147 | return b - t <= 0; 148 | } 149 | } 150 | } 151 | 152 | internal class CircularArray 153 | { 154 | readonly int baseSize; 155 | public readonly int size; 156 | public readonly T[] segment; 157 | 158 | public CircularArray (int baseSize) 159 | { 160 | this.baseSize = baseSize; 161 | this.size = 1 << baseSize; 162 | this.segment = new T[size]; 163 | } 164 | 165 | public int Size { 166 | get { 167 | return size; 168 | } 169 | } 170 | 171 | public T this[int index] { 172 | get { 173 | return segment[index % size]; 174 | } 175 | set { 176 | segment[index % size] = value; 177 | } 178 | } 179 | 180 | public CircularArray Grow (int bottom, int top) 181 | { 182 | var grow = new CircularArray (baseSize + 1); 183 | 184 | for (int i = top; i < bottom; i++) { 185 | grow.segment[i] = segment[i % size]; 186 | } 187 | 188 | return grow; 189 | } 190 | 191 | public IEnumerable GetEnumerable (int bottom, ref int top) 192 | { 193 | int instantTop = top; 194 | T[] slice = new T[bottom - instantTop]; 195 | int destIndex = -1; 196 | for (int i = instantTop; i < bottom; i++) 197 | slice[++destIndex] = segment[i % size]; 198 | 199 | return RealGetEnumerable (slice, bottom, top, instantTop); 200 | } 201 | 202 | IEnumerable RealGetEnumerable (T[] slice, int bottom, int realTop, int initialTop) 203 | { 204 | int destIndex = (int)(realTop - initialTop - 1); 205 | for (int i = realTop; i < bottom; ++i) 206 | yield return slice[++destIndex]; 207 | } 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /System.Threading.Tasks/IConcurrentDeque.cs: -------------------------------------------------------------------------------- 1 | // 2 | // IConcurrentDeque.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2011 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System.Collections.Generic; 28 | 29 | namespace System.Threading.Tasks 30 | { 31 | interface IConcurrentDeque 32 | { 33 | void PushBottom (T obj); 34 | PopResult PopBottom (out T obj); 35 | PopResult PopTop (out T obj); 36 | IEnumerable GetEnumerable (); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /System.Threading.Tasks/PopResult.cs: -------------------------------------------------------------------------------- 1 | // 2 | // PopResult.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2011 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | namespace System.Threading.Tasks 28 | { 29 | enum PopResult { 30 | Succeed, 31 | Empty, 32 | Abort 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /System.Threading.Tasks/SynchronizationContextScheduler.cs: -------------------------------------------------------------------------------- 1 | // 2 | // SynchronizationContextScheduler.cs 3 | // 4 | // Authors: 5 | // Jérémie "Garuma" Laval 6 | // Marek Safar 7 | // 8 | // Copyright (c) 2011 Novell 9 | // Copyright 2014 Xamarin Inc (http://www.xamarin.com). 10 | // 11 | // Permission is hereby granted, free of charge, to any person obtaining a copy 12 | // of this software and associated documentation files (the "Software"), to deal 13 | // in the Software without restriction, including without limitation the rights 14 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 15 | // copies of the Software, and to permit persons to whom the Software is 16 | // furnished to do so, subject to the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be included in 19 | // all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 27 | // THE SOFTWARE. 28 | 29 | using System.Threading; 30 | 31 | namespace System.Threading.Tasks 32 | { 33 | sealed class SynchronizationContextScheduler : TaskScheduler 34 | { 35 | readonly SynchronizationContext ctx; 36 | readonly SendOrPostCallback callback; 37 | 38 | public SynchronizationContextScheduler (SynchronizationContext ctx) 39 | { 40 | this.ctx = ctx; 41 | this.callback = TaskLaunchWrapper; 42 | } 43 | 44 | protected internal override void QueueTask (Task task) 45 | { 46 | ctx.Post (callback, task); 47 | } 48 | 49 | void TaskLaunchWrapper (object obj) 50 | { 51 | TryExecuteTask ((Task)obj); 52 | } 53 | 54 | protected override System.Collections.Generic.IEnumerable GetScheduledTasks () 55 | { 56 | throw new System.NotImplementedException(); 57 | } 58 | 59 | protected internal override bool TryDequeue (Task task) 60 | { 61 | return false; 62 | } 63 | 64 | protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued) 65 | { 66 | return ctx == SynchronizationContext.Current && TryExecuteTask (task); 67 | } 68 | 69 | public override int MaximumConcurrencyLevel { 70 | get { 71 | return 1; 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskCanceledException.cs: -------------------------------------------------------------------------------- 1 | // TaskCanceledException.cs 2 | // 3 | // Copyright (c) 2008 Jérémie "Garuma" Laval 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | // 23 | // 24 | 25 | using System; 26 | using System.Runtime.Serialization; 27 | 28 | namespace System.Threading.Tasks 29 | { 30 | [Serializable] 31 | public class TaskCanceledException : System.Couchbase.OperationCanceledException 32 | { 33 | readonly Task task; 34 | 35 | public TaskCanceledException (): base () 36 | { 37 | } 38 | 39 | public TaskCanceledException (string message): base (message) 40 | { 41 | } 42 | 43 | public TaskCanceledException (string message, Exception innerException): base (message, innerException) 44 | { 45 | } 46 | 47 | public TaskCanceledException (Task task): base ("The Task was canceled") 48 | { 49 | this.task = task; 50 | } 51 | 52 | protected TaskCanceledException (SerializationInfo info, StreamingContext context) 53 | : base (info, context) 54 | { 55 | 56 | } 57 | 58 | public Task Task { 59 | get { 60 | return task; 61 | } 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskCompletionQueue.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskCompletionQueue.cs 3 | // 4 | // Authors: 5 | // Jérémie Laval 6 | // 7 | // Copyright 2011 Xamarin Inc (http://www.xamarin.com). 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | // 27 | // 28 | 29 | using System.Threading; 30 | using System.Collections.Concurrent; 31 | 32 | namespace System.Threading.Tasks 33 | { 34 | internal struct TaskCompletionQueue where TCompletion : class 35 | { 36 | object single; //TCompletion 37 | TCompletion Single 38 | { 39 | get { return (TCompletion)single; } 40 | } 41 | object completed; //ConcurrentOrderedList 42 | ConcurrentOrderedList Completed 43 | { 44 | get { return (ConcurrentOrderedList)completed; } 45 | } 46 | 47 | public void Add (TCompletion continuation) 48 | { 49 | if (single == null && Interlocked.CompareExchange (ref single, continuation, null) == null) 50 | return; 51 | if (completed == null) 52 | Interlocked.CompareExchange (ref completed, new ConcurrentOrderedList (), null); 53 | Completed.TryAdd (continuation); 54 | } 55 | 56 | public bool Remove (TCompletion continuation) 57 | { 58 | TCompletion temp = Single; 59 | if (temp != null && temp == continuation && Interlocked.CompareExchange (ref single, null, continuation) == continuation) 60 | return true; 61 | if (completed != null) 62 | return Completed.TryRemove (continuation); 63 | return false; 64 | } 65 | 66 | public bool HasElements { 67 | get { 68 | return single != null || (completed != null && Completed.Count != 0); 69 | } 70 | } 71 | 72 | public bool TryGetNextCompletion (out TCompletion continuation) 73 | { 74 | continuation = null; 75 | 76 | if (single != null && (continuation = (TCompletion)Interlocked.Exchange (ref single, null)) != null) 77 | return true; 78 | 79 | return completed != null && Completed.TryPop (out continuation); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskCompletionSource.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskCompletionSource.cs 3 | // 4 | // Authors: 5 | // Jérémie "Garuma" Laval 6 | // Marek Safar 7 | // 8 | // Copyright (c) 2009 Jérémie "Garuma" Laval 9 | // Copyright 2011 Xamarin, Inc (http://www.xamarin.com) 10 | // 11 | // Permission is hereby granted, free of charge, to any person obtaining a copy 12 | // of this software and associated documentation files (the "Software"), to deal 13 | // in the Software without restriction, including without limitation the rights 14 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 15 | // copies of the Software, and to permit persons to whom the Software is 16 | // furnished to do so, subject to the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be included in 19 | // all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 27 | // THE SOFTWARE. 28 | 29 | using System; 30 | using System.Collections.Generic; 31 | 32 | namespace System.Threading.Tasks 33 | { 34 | public class TaskCompletionSource 35 | { 36 | readonly Task source; 37 | 38 | public TaskCompletionSource () 39 | : this (null, TaskCreationOptions.None) 40 | { 41 | } 42 | 43 | public TaskCompletionSource (object state) 44 | : this (state, TaskCreationOptions.None) 45 | { 46 | } 47 | 48 | public TaskCompletionSource (TaskCreationOptions creationOptions) 49 | : this (null, creationOptions) 50 | { 51 | } 52 | 53 | public TaskCompletionSource (object state, TaskCreationOptions creationOptions) 54 | { 55 | if ((creationOptions & System.Threading.Tasks.Task.WorkerTaskNotSupportedOptions) != 0) 56 | throw new ArgumentOutOfRangeException ("creationOptions"); 57 | 58 | source = new Task (TaskActionInvoker.Empty, state, CancellationToken.None, creationOptions, null); 59 | source.SetupScheduler (TaskScheduler.Current); 60 | } 61 | 62 | public void SetCanceled () 63 | { 64 | if (!TrySetCanceled ()) 65 | ThrowInvalidException (); 66 | } 67 | 68 | public void SetException (Exception exception) 69 | { 70 | if (exception == null) 71 | throw new ArgumentNullException ("exception"); 72 | 73 | SetException (new Exception[] { exception }); 74 | } 75 | 76 | public void SetException (IEnumerable exceptions) 77 | { 78 | if (!TrySetException (exceptions)) 79 | ThrowInvalidException (); 80 | } 81 | 82 | public void SetResult (TResult result) 83 | { 84 | if (!TrySetResult (result)) 85 | ThrowInvalidException (); 86 | } 87 | 88 | static void ThrowInvalidException () 89 | { 90 | throw new InvalidOperationException ("The underlying Task is already in one of the three final states: RanToCompletion, Faulted, or Canceled."); 91 | } 92 | 93 | public bool TrySetCanceled () 94 | { 95 | return source.TrySetCanceled (); 96 | } 97 | 98 | public bool TrySetException (Exception exception) 99 | { 100 | if (exception == null) 101 | throw new ArgumentNullException ("exception"); 102 | 103 | return TrySetException (new Exception[] { exception }); 104 | } 105 | 106 | public bool TrySetException (IEnumerable exceptions) 107 | { 108 | if (exceptions == null) 109 | throw new ArgumentNullException ("exceptions"); 110 | 111 | var aggregate = new AggregateException (exceptions); 112 | if (aggregate.InnerExceptions.Count == 0) 113 | throw new ArgumentNullException ("exceptions"); 114 | 115 | return source.TrySetException (aggregate, false, false); 116 | } 117 | 118 | public bool TrySetResult (TResult result) 119 | { 120 | return source.TrySetResult (result); 121 | } 122 | 123 | public Task Task { 124 | get { 125 | return source; 126 | } 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskConstants.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskConstants.cs 3 | // 4 | // Authors: 5 | // Jérémie Laval 6 | // 7 | // Copyright 2011 Xamarin Inc. 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | // 27 | // 28 | 29 | namespace System.Threading.Tasks 30 | { 31 | static class TaskConstants 32 | { 33 | public static readonly Task Finished; 34 | public static readonly Task Canceled; 35 | 36 | static TaskConstants () 37 | { 38 | var tcs = new TaskCompletionSource (); 39 | tcs.SetResult (null); 40 | Finished = tcs.Task; 41 | 42 | tcs = new TaskCompletionSource (); 43 | tcs.SetCanceled (); 44 | Canceled = tcs.Task; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskConstants_T.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskConstants_T.cs 3 | // 4 | // Authors: 5 | // Jérémie Laval 6 | // 7 | // Copyright 2011 Xamarin Inc. 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | // 27 | // 28 | 29 | #if NET_4_5 30 | 31 | namespace System.Threading.Tasks 32 | { 33 | internal class TaskConstants 34 | { 35 | internal static readonly Task Canceled; 36 | 37 | static TaskConstants () 38 | { 39 | var tcs = new TaskCompletionSource (); 40 | tcs.SetCanceled (); 41 | Canceled = tcs.Task; 42 | } 43 | } 44 | } 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskContinuationOptions.cs: -------------------------------------------------------------------------------- 1 | // TaskContinuationKind.cs 2 | // 3 | // Copyright (c) 2008 Jérémie "Garuma" Laval 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | // 23 | // 24 | 25 | namespace System.Threading.Tasks 26 | { 27 | [System.FlagsAttribute, System.SerializableAttribute] 28 | public enum TaskContinuationOptions 29 | { 30 | None = 0x00000, 31 | PreferFairness = 0x00001, 32 | LongRunning = 0x00002, 33 | AttachedToParent = 0x00004, 34 | #if NET_4_5 35 | DenyChildAttach = 0x00008, 36 | HideScheduler = 0x00010, 37 | LazyCancellation = 0x00020, 38 | #endif 39 | NotOnRanToCompletion = 0x10000, 40 | NotOnFaulted = 0x20000, 41 | NotOnCanceled = 0x40000, 42 | OnlyOnRanToCompletion = 0x60000, 43 | OnlyOnFaulted = 0x50000, 44 | OnlyOnCanceled = 0x30000, 45 | ExecuteSynchronously = 0x80000, 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskCreationOptions.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskCreationOptions.cs 3 | // 4 | // Authors: 5 | // Marek Safar (marek.safar@gmail.com) 6 | // 7 | // Copyright (c) 2008 Jérémie "Garuma" Laval 8 | // Copyright 2011 Xamarin Inc. 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining a copy 11 | // of this software and associated documentation files (the "Software"), to deal 12 | // in the Software without restriction, including without limitation the rights 13 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | // copies of the Software, and to permit persons to whom the Software is 15 | // furnished to do so, subject to the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be included in 18 | // all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 26 | // THE SOFTWARE. 27 | // 28 | // 29 | 30 | namespace System.Threading.Tasks 31 | { 32 | [FlagsAttribute, SerializableAttribute] 33 | public enum TaskCreationOptions 34 | { 35 | None = 0x0, 36 | PreferFairness = 0x1, 37 | LongRunning = 0x2, 38 | AttachedToParent = 0x4, 39 | #if NET_4_5 40 | DenyChildAttach = 0x8, 41 | HideScheduler = 0x10 42 | #endif 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskDebuggerView.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskDebuggerView.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // 7 | // Copyright 2011 Xamarin, Inc (http://www.xamarin.com) 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | using System; 30 | 31 | namespace System.Threading.Tasks 32 | { 33 | // 34 | // Custom debugger type proxy for tasks 35 | // 36 | sealed class TaskDebuggerView 37 | { 38 | readonly Task task; 39 | 40 | public TaskDebuggerView (Task task) 41 | { 42 | this.task = task; 43 | } 44 | 45 | public object AsyncState { 46 | get { 47 | return task.AsyncState; 48 | } 49 | } 50 | 51 | public TaskCreationOptions CreationOptions { 52 | get { 53 | return task.CreationOptions; 54 | } 55 | } 56 | 57 | public Exception Exception { 58 | get { 59 | return task.Exception; 60 | } 61 | } 62 | 63 | public int Id { 64 | get { 65 | return task.Id; 66 | } 67 | } 68 | 69 | public string Method { 70 | get { 71 | return task.DisplayActionMethod; 72 | } 73 | } 74 | 75 | public TaskStatus Status { 76 | get { 77 | return task.Status; 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskExceptionSlot.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskExceptionSlot.cs 3 | // 4 | // Authors: 5 | // Marek Safar 6 | // Jérémie Laval 7 | // 8 | // Copyright (c) 2008 Jérémie "Garuma" Laval 9 | // Copyright 2011 Xamarin Inc (http://www.xamarin.com). 10 | // 11 | // Permission is hereby granted, free of charge, to any person obtaining a copy 12 | // of this software and associated documentation files (the "Software"), to deal 13 | // in the Software without restriction, including without limitation the rights 14 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 15 | // copies of the Software, and to permit persons to whom the Software is 16 | // furnished to do so, subject to the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be included in 19 | // all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 27 | // THE SOFTWARE. 28 | // 29 | // 30 | 31 | using System; 32 | using System.Collections.Concurrent; 33 | 34 | namespace System.Threading.Tasks 35 | { 36 | internal class TaskExceptionSlot 37 | { 38 | public volatile AggregateException Exception; 39 | public volatile bool Observed; 40 | public object childExceptions; //ConcurrentQueue 41 | public ConcurrentQueue ChildExceptions 42 | { 43 | get { return (ConcurrentQueue)childExceptions; } 44 | } 45 | 46 | Task parent; 47 | 48 | public TaskExceptionSlot (Task parent) 49 | { 50 | this.parent = parent; 51 | } 52 | 53 | ~TaskExceptionSlot () 54 | { 55 | if (Exception != null && !Observed && !TaskScheduler.FireUnobservedEvent (parent, Exception).Observed) { 56 | // NET 4.5 changed the default exception behavior for unobserved exceptions. Unobserved exceptions still cause 57 | // the UnobservedTaskException event to be raised but the process will not crash by default 58 | // 59 | // .NET allows to configure this using config element ThrowUnobservedTaskExceptions 60 | // 61 | #if !NET_4_5 62 | throw Exception; 63 | #endif 64 | } 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskExtensions.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskExtensions.cs 3 | // 4 | // Authors: 5 | // Jérémie "Garuma" Laval 6 | // Marek Safar (marek.safar@gmail.com) 7 | // 8 | // Copyright (c) 2010 Jérémie "Garuma" Laval 9 | // Copyright (C) 2013 Xamarin, Inc (http://www.xamarin.com) 10 | // 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the 13 | // "Software"), to deal in the Software without restriction, including 14 | // without limitation the rights to use, copy, modify, merge, publish, 15 | // distribute, sublicense, and/or sell copies of the Software, and to 16 | // permit persons to whom the Software is furnished to do so, subject to 17 | // the following conditions: 18 | // 19 | // The above copyright notice and this permission notice shall be 20 | // included in all copies or substantial portions of the Software. 21 | // 22 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 23 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 24 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 25 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 26 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 27 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 28 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 29 | // 30 | 31 | namespace System.Threading.Tasks 32 | { 33 | public static class TaskExtensions 34 | { 35 | public static Task Unwrap (this Task> task) 36 | { 37 | if (task == null) 38 | throw new ArgumentNullException ("task"); 39 | 40 | return TaskExtensionsImpl.Unwrap (task); 41 | } 42 | 43 | public static Task Unwrap (this Task task) 44 | { 45 | if (task == null) 46 | throw new ArgumentNullException ("task"); 47 | 48 | return TaskExtensionsImpl.Unwrap (task); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskExtensionsImpl.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskExtensionsImpl.cs 3 | // 4 | // Authors: 5 | // Jérémie "Garuma" Laval 6 | // Marek Safar (marek.safar@gmail.com) 7 | // 8 | // Copyright (c) 2010 Jérémie "Garuma" Laval 9 | // Copyright (C) 2013 Xamarin, Inc (http://www.xamarin.com) 10 | // 11 | // Permission is hereby granted, free of charge, to any person obtaining 12 | // a copy of this software and associated documentation files (the 13 | // "Software"), to deal in the Software without restriction, including 14 | // without limitation the rights to use, copy, modify, merge, publish, 15 | // distribute, sublicense, and/or sell copies of the Software, and to 16 | // permit persons to whom the Software is furnished to do so, subject to 17 | // the following conditions: 18 | // 19 | // The above copyright notice and this permission notice shall be 20 | // included in all copies or substantial portions of the Software. 21 | // 22 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 23 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 24 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 25 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 26 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 27 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 28 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 29 | // 30 | 31 | namespace System.Threading.Tasks 32 | { 33 | public static class TaskExtensionsImpl 34 | { 35 | const TaskContinuationOptions options = TaskContinuationOptions.ExecuteSynchronously; 36 | 37 | public static Task Unwrap (Task> task) 38 | { 39 | var src = new TaskCompletionSource (); 40 | task.ContinueWith ((t, arg) => Cont (t, (TaskCompletionSource) arg), src, CancellationToken.None, options, TaskScheduler.Current); 41 | 42 | return src.Task; 43 | } 44 | 45 | public static Task Unwrap (Task task) 46 | { 47 | var src = new TaskCompletionSource (); 48 | task.ContinueWith ((t, arg) => Cont (t, (TaskCompletionSource) arg), src, CancellationToken.None, options, TaskScheduler.Current); 49 | 50 | return src.Task; 51 | } 52 | 53 | static void SetResult (Task source, TaskCompletionSource dest) 54 | { 55 | if (source.IsCanceled) 56 | dest.SetCanceled (); 57 | else if (source.IsFaulted) 58 | dest.SetException (source.Exception.InnerExceptions); 59 | else 60 | dest.SetResult (null); 61 | } 62 | 63 | static void Cont (Task source, TaskCompletionSource dest) 64 | { 65 | if (source.IsCanceled) 66 | dest.SetCanceled (); 67 | else if (source.IsFaulted) 68 | dest.SetException (source.Exception.InnerExceptions); 69 | else 70 | source.Result.ContinueWith ((t, arg) => SetResult (t, (TaskCompletionSource) arg), dest, CancellationToken.None, options, TaskScheduler.Current); 71 | } 72 | 73 | static void SetResult (Task source, TaskCompletionSource dest) 74 | { 75 | if (source.IsCanceled) 76 | dest.SetCanceled (); 77 | else if (source.IsFaulted) 78 | dest.SetException (source.Exception.InnerExceptions); 79 | else 80 | dest.SetResult (source.Result); 81 | } 82 | 83 | static void Cont (Task> source, TaskCompletionSource dest) 84 | { 85 | if (source.IsCanceled) 86 | dest.SetCanceled (); 87 | else if (source.IsFaulted) 88 | dest.SetException (source.Exception.InnerExceptions); 89 | else 90 | source.Result.ContinueWith ((t, arg) => SetResult (t, (TaskCompletionSource) arg), dest, CancellationToken.None, options, TaskScheduler.Current); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskScheduler.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskScheduler.cs 3 | // 4 | // Authors: 5 | // Jérémie "Garuma" Laval 6 | // Marek Safar 7 | // 8 | // Copyright (c) 2009 Jérémie "Garuma" Laval 9 | // Copyright 2012 Xamarin, Inc (http://www.xamarin.com) 10 | // 11 | // Permission is hereby granted, free of charge, to any person obtaining a copy 12 | // of this software and associated documentation files (the "Software"), to deal 13 | // in the Software without restriction, including without limitation the rights 14 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 15 | // copies of the Software, and to permit persons to whom the Software is 16 | // furnished to do so, subject to the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be included in 19 | // all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 27 | // THE SOFTWARE. 28 | 29 | using System.Collections.Generic; 30 | using System.Diagnostics; 31 | 32 | namespace System.Threading.Tasks 33 | { 34 | [DebuggerDisplay ("Id={Id}")] 35 | [DebuggerTypeProxy (typeof (TaskSchedulerDebuggerView))] 36 | public abstract class TaskScheduler 37 | { 38 | sealed class TaskSchedulerDebuggerView 39 | { 40 | readonly TaskScheduler scheduler; 41 | 42 | public TaskSchedulerDebuggerView (TaskScheduler scheduler) 43 | { 44 | this.scheduler = scheduler; 45 | } 46 | 47 | public IEnumerable ScheduledTasks { 48 | get { 49 | return scheduler.GetScheduledTasks (); 50 | } 51 | } 52 | } 53 | 54 | static readonly TaskScheduler defaultScheduler = new TpScheduler (); 55 | 56 | [ThreadStatic] 57 | static TaskScheduler currentScheduler; 58 | 59 | int id; 60 | static int lastId = int.MinValue; 61 | 62 | public static event EventHandler UnobservedTaskException; 63 | 64 | protected TaskScheduler () 65 | { 66 | this.id = Interlocked.Increment (ref lastId); 67 | } 68 | 69 | public static TaskScheduler FromCurrentSynchronizationContext () 70 | { 71 | var syncCtx = SynchronizationContext.Current; 72 | if (syncCtx == null) 73 | throw new InvalidOperationException ("The current SynchronizationContext is null and cannot be used as a TaskScheduler"); 74 | 75 | return new SynchronizationContextScheduler (syncCtx); 76 | } 77 | 78 | public static TaskScheduler Default { 79 | get { 80 | return defaultScheduler; 81 | } 82 | } 83 | 84 | public static TaskScheduler Current { 85 | get { 86 | if (currentScheduler != null) 87 | return currentScheduler; 88 | 89 | return defaultScheduler; 90 | } 91 | internal set { 92 | currentScheduler = value; 93 | } 94 | } 95 | 96 | public int Id { 97 | get { 98 | return id; 99 | } 100 | } 101 | 102 | internal static bool IsDefault { 103 | get { 104 | return currentScheduler == null || currentScheduler == defaultScheduler; 105 | } 106 | } 107 | 108 | public virtual int MaximumConcurrencyLevel { 109 | get { 110 | return int.MaxValue; 111 | } 112 | } 113 | 114 | protected abstract IEnumerable GetScheduledTasks (); 115 | protected internal abstract void QueueTask (Task task); 116 | 117 | protected internal virtual bool TryDequeue (Task task) 118 | { 119 | return false; 120 | } 121 | 122 | internal protected bool TryExecuteTask (Task task) 123 | { 124 | if (task.IsCompleted) 125 | return false; 126 | 127 | if (task.Status == TaskStatus.WaitingToRun) { 128 | task.Execute (); 129 | if (task.WaitOnChildren ()) 130 | task.Wait (); 131 | 132 | return true; 133 | } 134 | 135 | return false; 136 | } 137 | 138 | protected abstract bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued); 139 | 140 | internal bool RunInline (Task task, bool taskWasPreviouslyQueued) 141 | { 142 | if (!TryExecuteTaskInline (task, taskWasPreviouslyQueued)) 143 | return false; 144 | 145 | if (!task.IsCompleted) 146 | throw new InvalidOperationException ("The TryExecuteTaskInline call to the underlying scheduler succeeded, but the task body was not invoked"); 147 | 148 | return true; 149 | } 150 | 151 | internal static UnobservedTaskExceptionEventArgs FireUnobservedEvent (Task task, AggregateException e) 152 | { 153 | UnobservedTaskExceptionEventArgs args = new UnobservedTaskExceptionEventArgs (e); 154 | 155 | EventHandler temp = UnobservedTaskException; 156 | if (temp == null) 157 | return args; 158 | 159 | temp (task, args); 160 | 161 | return args; 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskSchedulerException.cs: -------------------------------------------------------------------------------- 1 | // TaskSchedulerException.cs 2 | // 3 | // Copyright (c) 2008 Jérémie "Garuma" Laval 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | // 23 | // 24 | 25 | using System; 26 | using System.Runtime.Serialization; 27 | 28 | namespace System.Threading.Tasks 29 | { 30 | public class TaskSchedulerException : Exception 31 | { 32 | const string exceptionDefaultMessage = "An exception was thrown by a TaskScheduler"; 33 | 34 | public TaskSchedulerException () : base (exceptionDefaultMessage) 35 | { 36 | 37 | } 38 | 39 | public TaskSchedulerException (string message) : base (message) 40 | { 41 | 42 | } 43 | 44 | protected TaskSchedulerException (SerializationInfo info, StreamingContext context) 45 | : base (info, context) 46 | { 47 | 48 | } 49 | 50 | public TaskSchedulerException (Exception innerException) 51 | : base (exceptionDefaultMessage, innerException) 52 | { 53 | 54 | } 55 | 56 | public TaskSchedulerException (string message, Exception innerException) 57 | : base (message, innerException) 58 | { 59 | 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TaskStatus.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TaskStatus.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2009 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | namespace System.Threading.Tasks 28 | { 29 | public enum TaskStatus 30 | { 31 | Created, 32 | WaitingForActivation, 33 | WaitingToRun, 34 | Running, 35 | WaitingForChildrenToComplete, 36 | RanToCompletion, 37 | Canceled, 38 | Faulted 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /System.Threading.Tasks/TpScheduler.cs: -------------------------------------------------------------------------------- 1 | // 2 | // TpScheduler.cs 3 | // 4 | // Authors: 5 | // Jérémie Laval 6 | // Marek Safar 7 | // 8 | // Copyright (c) 2011 Jérémie "Garuma" Laval 9 | // Copyright 2012 Xamarin Inc (http://www.xamarin.com). 10 | // 11 | // 12 | // Permission is hereby granted, free of charge, to any person obtaining a copy 13 | // of this software and associated documentation files (the "Software"), to deal 14 | // in the Software without restriction, including without limitation the rights 15 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 16 | // copies of the Software, and to permit persons to whom the Software is 17 | // furnished to do so, subject to the following conditions: 18 | // 19 | // The above copyright notice and this permission notice shall be included in 20 | // all copies or substantial portions of the Software. 21 | // 22 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 25 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 28 | // THE SOFTWARE. 29 | // 30 | // 31 | 32 | using System.Collections.Generic; 33 | 34 | namespace System.Threading.Tasks 35 | { 36 | sealed class TpScheduler: TaskScheduler 37 | { 38 | static readonly WaitCallback callback = TaskExecuterCallback; 39 | 40 | protected internal override void QueueTask (Task task) 41 | { 42 | if ((task.CreationOptions & TaskCreationOptions.LongRunning) != 0) { 43 | var thread = new Thread (l => ((Task)l).Execute ()) { 44 | IsBackground = true 45 | }; 46 | 47 | thread.Start (task); 48 | return; 49 | } 50 | 51 | ThreadPool.QueueUserWorkItem (callback, task); 52 | } 53 | 54 | static void TaskExecuterCallback (object obj) 55 | { 56 | Task task = (Task)obj; 57 | task.Execute (); 58 | } 59 | 60 | protected override IEnumerable GetScheduledTasks () 61 | { 62 | throw new NotImplementedException(); 63 | } 64 | 65 | 66 | protected internal override bool TryDequeue (Task task) 67 | { 68 | return false; 69 | } 70 | 71 | protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued) 72 | { 73 | if (taskWasPreviouslyQueued && !TryDequeue (task)) 74 | return false; 75 | 76 | return TryExecuteTask (task); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /System.Threading.Tasks/UnobservedTaskExceptionEventArgs.cs: -------------------------------------------------------------------------------- 1 | // 2 | // UnobservedTaskExceptionEventArgs.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2010 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System; 28 | 29 | namespace System.Threading.Tasks 30 | { 31 | public class UnobservedTaskExceptionEventArgs : EventArgs 32 | { 33 | AggregateException exception; 34 | bool wasObserved; 35 | 36 | public UnobservedTaskExceptionEventArgs (AggregateException exception) 37 | { 38 | this.exception = exception; 39 | } 40 | 41 | public AggregateException Exception { 42 | get { 43 | return exception; 44 | } 45 | } 46 | 47 | public bool Observed { 48 | get { 49 | return wasObserved; 50 | } 51 | } 52 | 53 | public void SetObserved () 54 | { 55 | wasObserved = true; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /System.Threading/AtomicBoolean.cs: -------------------------------------------------------------------------------- 1 | // AtomicBoolean.cs 2 | // 3 | // Copyright (c) 2008 Jérémie "Garuma" Laval 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | // 23 | // 24 | 25 | namespace System.Threading 26 | { 27 | struct AtomicBooleanValue 28 | { 29 | int flag; 30 | const int UnSet = 0; 31 | const int Set = 1; 32 | 33 | public bool CompareAndExchange (bool expected, bool newVal) 34 | { 35 | int newTemp = newVal ? Set : UnSet; 36 | int expectedTemp = expected ? Set : UnSet; 37 | 38 | return Interlocked.CompareExchange (ref flag, newTemp, expectedTemp) == expectedTemp; 39 | } 40 | 41 | public static AtomicBooleanValue FromValue (bool value) 42 | { 43 | AtomicBooleanValue temp = new AtomicBooleanValue (); 44 | temp.Value = value; 45 | 46 | return temp; 47 | } 48 | 49 | public bool TrySet () 50 | { 51 | return !Exchange (true); 52 | } 53 | 54 | public bool TryRelaxedSet () 55 | { 56 | return flag == UnSet && !Exchange (true); 57 | } 58 | 59 | public bool Exchange (bool newVal) 60 | { 61 | int newTemp = newVal ? Set : UnSet; 62 | return Interlocked.Exchange (ref flag, newTemp) == Set; 63 | } 64 | 65 | public bool Value { 66 | get { 67 | return flag == Set; 68 | } 69 | set { 70 | Exchange (value); 71 | } 72 | } 73 | 74 | public bool Equals (AtomicBooleanValue rhs) 75 | { 76 | return this.flag == rhs.flag; 77 | } 78 | 79 | public override bool Equals (object rhs) 80 | { 81 | return rhs is AtomicBooleanValue ? Equals ((AtomicBooleanValue)rhs) : false; 82 | } 83 | 84 | public override int GetHashCode () 85 | { 86 | return flag.GetHashCode (); 87 | } 88 | 89 | public static explicit operator bool (AtomicBooleanValue rhs) 90 | { 91 | return rhs.Value; 92 | } 93 | 94 | public static implicit operator AtomicBooleanValue (bool rhs) 95 | { 96 | return AtomicBooleanValue.FromValue (rhs); 97 | } 98 | } 99 | 100 | class AtomicBoolean 101 | { 102 | int flag; 103 | const int UnSet = 0; 104 | const int Set = 1; 105 | 106 | public bool CompareAndExchange (bool expected, bool newVal) 107 | { 108 | int newTemp = newVal ? Set : UnSet; 109 | int expectedTemp = expected ? Set : UnSet; 110 | 111 | return Interlocked.CompareExchange (ref flag, newTemp, expectedTemp) == expectedTemp; 112 | } 113 | 114 | public static AtomicBoolean FromValue (bool value) 115 | { 116 | AtomicBoolean temp = new AtomicBoolean (); 117 | temp.Value = value; 118 | 119 | return temp; 120 | } 121 | 122 | public bool TrySet () 123 | { 124 | return !Exchange (true); 125 | } 126 | 127 | public bool TryRelaxedSet () 128 | { 129 | return flag == UnSet && !Exchange (true); 130 | } 131 | 132 | public bool Exchange (bool newVal) 133 | { 134 | int newTemp = newVal ? Set : UnSet; 135 | return Interlocked.Exchange (ref flag, newTemp) == Set; 136 | } 137 | 138 | public bool Value { 139 | get { 140 | return flag == Set; 141 | } 142 | set { 143 | Exchange (value); 144 | } 145 | } 146 | 147 | public bool Equals (AtomicBoolean rhs) 148 | { 149 | return this.flag == rhs.flag; 150 | } 151 | 152 | public override bool Equals (object rhs) 153 | { 154 | return rhs is AtomicBoolean ? Equals ((AtomicBoolean)rhs) : false; 155 | } 156 | 157 | public override int GetHashCode () 158 | { 159 | return flag.GetHashCode (); 160 | } 161 | 162 | public static explicit operator bool (AtomicBoolean rhs) 163 | { 164 | return rhs.Value; 165 | } 166 | 167 | public static implicit operator AtomicBoolean (bool rhs) 168 | { 169 | return AtomicBoolean.FromValue (rhs); 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /System.Threading/CancellationToken.cs: -------------------------------------------------------------------------------- 1 | // 2 | // CancellationToken.cs 3 | // 4 | // Authors: 5 | // Jérémie "Garuma" Laval 6 | // Marek Safar (marek.safar@gmail.com) 7 | // 8 | // Copyright (c) 2009 Jérémie "Garuma" Laval 9 | // Copyright 2011 Xamarin, Inc (http://www.xamarin.com) 10 | // 11 | // Permission is hereby granted, free of charge, to any person obtaining a copy 12 | // of this software and associated documentation files (the "Software"), to deal 13 | // in the Software without restriction, including without limitation the rights 14 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 15 | // copies of the Software, and to permit persons to whom the Software is 16 | // furnished to do so, subject to the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be included in 19 | // all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 27 | // THE SOFTWARE. 28 | 29 | using System; 30 | using System.Threading; 31 | using System.Diagnostics; 32 | 33 | namespace System.Threading 34 | { 35 | [DebuggerDisplay ("IsCancellationRequested = {IsCancellationRequested}")] 36 | public struct CancellationToken 37 | { 38 | readonly CancellationTokenSource source; 39 | 40 | public CancellationToken (bool canceled) 41 | : this (canceled ? CancellationTokenSource.CanceledSource : null) 42 | { 43 | } 44 | 45 | internal CancellationToken (CancellationTokenSource source) 46 | { 47 | this.source = source; 48 | } 49 | 50 | public static CancellationToken None { 51 | get { 52 | // simply return new struct value, it's the fastest option 53 | // and we don't have to bother with reseting source 54 | return new CancellationToken (); 55 | } 56 | } 57 | 58 | public CancellationTokenRegistration Register (Action callback) 59 | { 60 | return Register (callback, false); 61 | } 62 | 63 | public CancellationTokenRegistration Register (Action callback, bool useSynchronizationContext) 64 | { 65 | if (callback == null) 66 | throw new ArgumentNullException ("callback"); 67 | 68 | return Source.Register (callback, useSynchronizationContext); 69 | } 70 | 71 | public CancellationTokenRegistration Register (Action callback, object state) 72 | { 73 | return Register (callback, state, false); 74 | } 75 | 76 | public CancellationTokenRegistration Register (Action callback, object state, bool useSynchronizationContext) 77 | { 78 | if (callback == null) 79 | throw new ArgumentNullException ("callback"); 80 | 81 | return Register (() => callback (state), useSynchronizationContext); 82 | } 83 | 84 | public void ThrowIfCancellationRequested () 85 | { 86 | if (source != null && source.IsCancellationRequested) 87 | throw new System.Couchbase.OperationCanceledException (this); 88 | } 89 | 90 | public bool Equals (CancellationToken other) 91 | { 92 | return this.Source == other.Source; 93 | } 94 | 95 | public override bool Equals (object other) 96 | { 97 | return (other is CancellationToken) ? Equals ((CancellationToken)other) : false; 98 | } 99 | 100 | public override int GetHashCode () 101 | { 102 | return Source.GetHashCode (); 103 | } 104 | 105 | public static bool operator == (CancellationToken left, CancellationToken right) 106 | { 107 | return left.Equals (right); 108 | } 109 | 110 | public static bool operator != (CancellationToken left, CancellationToken right) 111 | { 112 | return !left.Equals (right); 113 | } 114 | 115 | public bool CanBeCanceled { 116 | get { 117 | return source != null; 118 | } 119 | } 120 | 121 | public bool IsCancellationRequested { 122 | get { 123 | return Source.IsCancellationRequested; 124 | } 125 | } 126 | 127 | public WaitHandle WaitHandle { 128 | get { 129 | return Source.WaitHandle; 130 | } 131 | } 132 | 133 | CancellationTokenSource Source { 134 | get { 135 | return source ?? CancellationTokenSource.NoneSource; 136 | } 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /System.Threading/CancellationTokenRegistration.cs: -------------------------------------------------------------------------------- 1 | // 2 | // CancellationTokenRegistration.cs 3 | // 4 | // Author: 5 | // Jérémie "Garuma" Laval 6 | // 7 | // Copyright (c) 2009 Jérémie "Garuma" Laval 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | 27 | using System; 28 | 29 | namespace System.Threading 30 | { 31 | public struct CancellationTokenRegistration: IDisposable, IEquatable 32 | { 33 | readonly int id; 34 | readonly CancellationTokenSource source; 35 | 36 | internal CancellationTokenRegistration (int id, CancellationTokenSource source) 37 | { 38 | this.id = id; 39 | this.source = source; 40 | } 41 | 42 | #region IDisposable implementation 43 | public void Dispose () 44 | { 45 | if (source != null) 46 | source.RemoveCallback (this); 47 | } 48 | #endregion 49 | 50 | #region IEquatable implementation 51 | public bool Equals (CancellationTokenRegistration other) 52 | { 53 | return id == other.id && source == other.source; 54 | } 55 | 56 | public static bool operator== (CancellationTokenRegistration left, CancellationTokenRegistration right) 57 | { 58 | return left.Equals (right); 59 | } 60 | 61 | public static bool operator!= (CancellationTokenRegistration left, CancellationTokenRegistration right) 62 | { 63 | return !left.Equals (right); 64 | } 65 | #endregion 66 | 67 | public override int GetHashCode () 68 | { 69 | return id.GetHashCode () ^ (source == null ? 0 : source.GetHashCode ()); 70 | } 71 | 72 | public override bool Equals (object obj) 73 | { 74 | return (obj is CancellationTokenRegistration) && Equals ((CancellationTokenRegistration)obj); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /System.Threading/CountdownEvent.cs: -------------------------------------------------------------------------------- 1 | // CountdownEvent.cs 2 | // 3 | // Authors: 4 | // Marek Safar 5 | // 6 | // Copyright (c) 2008 Jérémie "Garuma" Laval 7 | // Copyright 2011 Xamarin Inc (http://www.xamarin.com). 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining a copy 10 | // of this software and associated documentation files (the "Software"), to deal 11 | // in the Software without restriction, including without limitation the rights 12 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the Software is 14 | // furnished to do so, subject to the following conditions: 15 | // 16 | // The above copyright notice and this permission notice shall be included in 17 | // all copies or substantial portions of the Software. 18 | // 19 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | // THE SOFTWARE. 26 | // 27 | // 28 | 29 | namespace System.Threading 30 | { 31 | [System.Diagnostics.DebuggerDisplayAttribute ("Initial Count={InitialCount}, Current Count={CurrentCount}")] 32 | public class CountdownEvent : IDisposable 33 | { 34 | int initialCount; 35 | int initial; 36 | ManualResetEventSlim evt; 37 | 38 | public CountdownEvent (int initialCount) 39 | { 40 | if (initialCount < 0) 41 | throw new ArgumentOutOfRangeException ("initialCount"); 42 | 43 | evt = new ManualResetEventSlim (initialCount == 0); 44 | this.initial = this.initialCount = initialCount; 45 | } 46 | 47 | public int CurrentCount { 48 | get { 49 | return initialCount; 50 | } 51 | } 52 | 53 | public int InitialCount { 54 | get { 55 | return initial; 56 | } 57 | } 58 | 59 | public bool IsSet { 60 | get { 61 | return initialCount == 0; 62 | } 63 | } 64 | 65 | public WaitHandle WaitHandle { 66 | get { 67 | return evt.WaitHandle; 68 | } 69 | } 70 | 71 | public bool Signal () 72 | { 73 | return Signal (1); 74 | } 75 | 76 | public bool Signal (int signalCount) 77 | { 78 | if (signalCount <= 0) 79 | throw new ArgumentOutOfRangeException ("signalCount"); 80 | 81 | CheckDisposed (); 82 | 83 | int newValue; 84 | if (!ApplyOperation (-signalCount, out newValue)) 85 | throw new InvalidOperationException ("The event is already set"); 86 | 87 | if (newValue == 0) { 88 | evt.Set (); 89 | return true; 90 | } 91 | 92 | return false; 93 | } 94 | 95 | public void AddCount () 96 | { 97 | AddCount (1); 98 | } 99 | 100 | public void AddCount (int signalCount) 101 | { 102 | if (!TryAddCount (signalCount)) 103 | throw new InvalidOperationException ("The event is already signaled and cannot be incremented"); 104 | } 105 | 106 | public bool TryAddCount () 107 | { 108 | return TryAddCount (1); 109 | } 110 | 111 | public bool TryAddCount (int signalCount) 112 | { 113 | if (signalCount <= 0) 114 | throw new ArgumentOutOfRangeException ("signalCount"); 115 | 116 | CheckDisposed (); 117 | 118 | int temp; 119 | return ApplyOperation (signalCount, out temp); 120 | } 121 | 122 | bool ApplyOperation (int num, out int newValue) 123 | { 124 | int oldCount; 125 | 126 | do { 127 | oldCount = initialCount; 128 | if (oldCount == 0) { 129 | newValue = 0; 130 | return false; 131 | } 132 | 133 | newValue = oldCount + num; 134 | 135 | if (newValue < 0) 136 | return false; 137 | } while (Interlocked.CompareExchange (ref initialCount, newValue, oldCount) != oldCount); 138 | 139 | return true; 140 | } 141 | 142 | public void Wait () 143 | { 144 | evt.Wait (); 145 | } 146 | 147 | public void Wait (CancellationToken cancellationToken) 148 | { 149 | evt.Wait (cancellationToken); 150 | } 151 | 152 | public bool Wait (int millisecondsTimeout) 153 | { 154 | return evt.Wait (millisecondsTimeout); 155 | } 156 | 157 | public bool Wait(TimeSpan timeout) 158 | { 159 | return evt.Wait (timeout); 160 | } 161 | 162 | public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken) 163 | { 164 | return evt.Wait (millisecondsTimeout, cancellationToken); 165 | } 166 | 167 | public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) 168 | { 169 | return evt.Wait (timeout, cancellationToken); 170 | } 171 | 172 | public void Reset () 173 | { 174 | Reset (initial); 175 | } 176 | 177 | public void Reset (int count) 178 | { 179 | if (count < 0) 180 | throw new ArgumentOutOfRangeException ("count"); 181 | 182 | CheckDisposed (); 183 | 184 | initialCount = initial = count; 185 | if (count == 0) 186 | evt.Set (); 187 | else 188 | evt.Reset (); 189 | } 190 | 191 | public void Dispose () 192 | { 193 | Dispose (true); 194 | } 195 | 196 | protected virtual void Dispose (bool disposing) 197 | { 198 | if (disposing) 199 | evt.Dispose (); 200 | } 201 | 202 | void CheckDisposed () 203 | { 204 | if (evt.disposed.Value) 205 | throw new ObjectDisposedException ("CountdownEvent"); 206 | } 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /System.Threading/SpinWait.cs: -------------------------------------------------------------------------------- 1 | // SpinWait.cs 2 | // 3 | // Copyright (c) 2008 Jérémie "Garuma" Laval 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | // 23 | // 24 | 25 | using System; 26 | 27 | namespace System.Threading 28 | { 29 | public struct SpinWait 30 | { 31 | // The number of step until SpinOnce yield on multicore machine 32 | const int step = 10; 33 | const int maxTime = 200; 34 | static readonly bool isSingleCpu = (Environment.ProcessorCount == 1); 35 | 36 | int ntime; 37 | 38 | public void SpinOnce () 39 | { 40 | ntime += 1; 41 | 42 | if (isSingleCpu) { 43 | // On a single-CPU system, spinning does no good 44 | Thread.Sleep (0); 45 | } else { 46 | if (ntime % step == 0) 47 | Thread.Sleep (0); 48 | else 49 | // Multi-CPU system might be hyper-threaded, let other thread run 50 | Thread.SpinWait (Math.Min (ntime, maxTime) << 1); 51 | } 52 | } 53 | 54 | public static void SpinUntil (Func condition) 55 | { 56 | SpinWait sw = new SpinWait (); 57 | while (!condition ()) 58 | sw.SpinOnce (); 59 | } 60 | 61 | public static bool SpinUntil (Func condition, TimeSpan timeout) 62 | { 63 | return SpinUntil (condition, (int)timeout.TotalMilliseconds); 64 | } 65 | 66 | public static bool SpinUntil (Func condition, int millisecondsTimeout) 67 | { 68 | SpinWait sw = new SpinWait (); 69 | Watch watch = Watch.StartNew (); 70 | 71 | while (!condition ()) { 72 | if (watch.ElapsedMilliseconds > millisecondsTimeout) 73 | return false; 74 | sw.SpinOnce (); 75 | } 76 | 77 | return true; 78 | } 79 | 80 | public void Reset () 81 | { 82 | ntime = 0; 83 | } 84 | 85 | public bool NextSpinWillYield { 86 | get { 87 | return isSingleCpu ? true : ntime % step == 0; 88 | } 89 | } 90 | 91 | public int Count { 92 | get { 93 | return ntime; 94 | } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /System.Threading/Watch.cs: -------------------------------------------------------------------------------- 1 | // Task.cs 2 | // 3 | // Copyright (c) 2008 Jérémie "Garuma" Laval 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | // 23 | // 24 | 25 | using System; 26 | 27 | namespace System.Threading 28 | { 29 | internal struct Watch 30 | { 31 | long startTicks; 32 | 33 | public static Watch StartNew () 34 | { 35 | Watch watch = new Watch (); 36 | watch.Start (); 37 | return watch; 38 | } 39 | 40 | public void Start () 41 | { 42 | startTicks = TicksNow (); 43 | } 44 | 45 | public void Stop () 46 | { 47 | 48 | } 49 | 50 | public long ElapsedMilliseconds { 51 | get { 52 | return (TicksNow () - startTicks) / TimeSpan.TicksPerMillisecond; 53 | } 54 | } 55 | 56 | static long TicksNow () 57 | { 58 | return DateTime.Now.Ticks; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /System/AggregateException.cs: -------------------------------------------------------------------------------- 1 | // 2 | // AggregateException.cs 3 | // 4 | // Authors: 5 | // Marek Safar (marek.safar@gmail.com) 6 | // 7 | // Copyright (c) 2008 Jérémie "Garuma" Laval 8 | // Copyright (C) 2013 Xamarin Inc (http://www.xamarin.com) 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining a copy 11 | // of this software and associated documentation files (the "Software"), to deal 12 | // in the Software without restriction, including without limitation the rights 13 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | // copies of the Software, and to permit persons to whom the Software is 15 | // furnished to do so, subject to the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be included in 18 | // all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 26 | // THE SOFTWARE. 27 | // 28 | // 29 | 30 | using System; 31 | using System.Collections.ObjectModel; 32 | using System.Collections.Generic; 33 | using System.Runtime.Serialization; 34 | 35 | namespace System 36 | { 37 | [System.SerializableAttribute] 38 | [System.Diagnostics.DebuggerDisplay ("Count = {InnerExceptions.Count}")] 39 | public class AggregateException : Exception 40 | { 41 | List innerExceptions = new List (); 42 | const string defaultMessage = "One or more errors occurred"; 43 | 44 | public AggregateException () : base (defaultMessage) 45 | { 46 | } 47 | 48 | public AggregateException (string message): base (message) 49 | { 50 | } 51 | 52 | public AggregateException (string message, Exception innerException): base (message, innerException) 53 | { 54 | if (innerException == null) 55 | throw new ArgumentNullException ("innerException"); 56 | innerExceptions.Add (innerException); 57 | } 58 | 59 | protected AggregateException (SerializationInfo info, StreamingContext context) 60 | : base (info, context) 61 | { 62 | } 63 | 64 | public AggregateException (params Exception[] innerExceptions) 65 | : this (defaultMessage, innerExceptions) 66 | { 67 | } 68 | 69 | public AggregateException (string message, params Exception[] innerExceptions) 70 | : base (message, innerExceptions == null || innerExceptions.Length == 0 ? null : innerExceptions[0]) 71 | { 72 | if (innerExceptions == null) 73 | throw new ArgumentNullException ("innerExceptions"); 74 | foreach (var exception in innerExceptions) 75 | if (exception == null) 76 | throw new ArgumentException ("One of the inner exception is null", "innerExceptions"); 77 | 78 | this.innerExceptions.AddRange (innerExceptions); 79 | } 80 | 81 | public AggregateException (IEnumerable innerExceptions) 82 | : this (defaultMessage, innerExceptions) 83 | { 84 | } 85 | 86 | public AggregateException (string message, IEnumerable innerExceptions) 87 | : this (message, new List (innerExceptions).ToArray ()) 88 | { 89 | } 90 | 91 | public AggregateException Flatten () 92 | { 93 | List inner = new List (); 94 | 95 | foreach (Exception e in innerExceptions) { 96 | AggregateException aggEx = e as AggregateException; 97 | if (aggEx != null) { 98 | inner.AddRange (aggEx.Flatten ().InnerExceptions); 99 | } else { 100 | inner.Add (e); 101 | } 102 | } 103 | 104 | return new AggregateException (inner); 105 | } 106 | 107 | public void Handle (Func predicate) 108 | { 109 | if (predicate == null) 110 | throw new ArgumentNullException ("predicate"); 111 | 112 | List failed = new List (); 113 | foreach (var e in innerExceptions) { 114 | if (!predicate (e)) 115 | failed.Add (e); 116 | } 117 | 118 | if (failed.Count > 0) 119 | throw new AggregateException (failed); 120 | } 121 | 122 | public ReadOnlyCollection InnerExceptions { 123 | get { 124 | return innerExceptions.AsReadOnly (); 125 | } 126 | } 127 | 128 | internal void AddChildException (AggregateException childEx) 129 | { 130 | if (innerExceptions == null) 131 | innerExceptions = new List (); 132 | if (childEx == null) 133 | return; 134 | 135 | innerExceptions.Add (childEx); 136 | } 137 | 138 | public override string ToString () 139 | { 140 | System.Text.StringBuilder finalMessage = new System.Text.StringBuilder (base.ToString ()); 141 | 142 | int currentIndex = -1; 143 | foreach (Exception e in innerExceptions) { 144 | finalMessage.Append (Environment.NewLine); 145 | finalMessage.Append (" --> (Inner exception "); 146 | finalMessage.Append (++currentIndex); 147 | finalMessage.Append (") "); 148 | finalMessage.Append (e.ToString ()); 149 | finalMessage.Append (Environment.NewLine); 150 | } 151 | return finalMessage.ToString (); 152 | } 153 | 154 | public override void GetObjectData (SerializationInfo info, StreamingContext context) 155 | { 156 | if (info == null) { 157 | throw new ArgumentNullException("info"); 158 | } 159 | base.GetObjectData(info, context); 160 | info.AddValue ("InnerExceptions", innerExceptions.ToArray(), typeof (Exception[])); 161 | } 162 | 163 | public override Exception GetBaseException () 164 | { 165 | Exception inner = this; 166 | for (var ae = this; ae.innerExceptions.Count == 1;) { 167 | inner = ae.InnerExceptions [0]; 168 | 169 | var aei = inner as AggregateException; 170 | if (aei == null) 171 | break; 172 | 173 | ae = aei; 174 | } 175 | 176 | return inner; 177 | } 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /System/Funcs.cs: -------------------------------------------------------------------------------- 1 | // 2 | // System.Func.cs 3 | // 4 | // Authors: 5 | // Alejandro Serrano "Serras" (trupill@yahoo.es) 6 | // Marek Safar (marek.safar@gmail.com) 7 | // 8 | 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR TArg PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // 27 | 28 | namespace System { 29 | 30 | public delegate TResult Func (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); 31 | public delegate TResult Func (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); 32 | public delegate TResult Func (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); 33 | public delegate TResult Func (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /System/Lazy.cs: -------------------------------------------------------------------------------- 1 | // 2 | // Lazy.cs 3 | // 4 | // Authors: 5 | // Zoltan Varga (vargaz@gmail.com) 6 | // Marek Safar (marek.safar@gmail.com) 7 | // 8 | // Copyright (C) 2009 Novell 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining 11 | // a copy of this software and associated documentation files (the 12 | // "Software"), to deal in the Software without restriction, including 13 | // without limitation the rights to use, copy, modify, merge, publish, 14 | // distribute, sublicense, and/or sell copies of the Software, and to 15 | // permit persons to whom the Software is furnished to do so, subject to 16 | // the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | using System; 31 | using System.Runtime.Serialization; 32 | using System.Runtime.InteropServices; 33 | using System.Security.Permissions; 34 | using System.Threading; 35 | using System.Diagnostics; 36 | 37 | namespace System 38 | { 39 | [SerializableAttribute] 40 | [ComVisibleAttribute(false)] 41 | [HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)] 42 | [DebuggerDisplay ("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")] 43 | public class Lazy 44 | { 45 | T value; 46 | Func factory; 47 | object monitor; 48 | Exception exception; 49 | LazyThreadSafetyMode mode; 50 | bool inited; 51 | 52 | public Lazy () 53 | : this (LazyThreadSafetyMode.ExecutionAndPublication) 54 | { 55 | } 56 | 57 | public Lazy (Func valueFactory) 58 | : this (valueFactory, LazyThreadSafetyMode.ExecutionAndPublication) 59 | { 60 | } 61 | 62 | public Lazy (bool isThreadSafe) 63 | : this (Activator.CreateInstance, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) 64 | { 65 | } 66 | 67 | public Lazy (Func valueFactory, bool isThreadSafe) 68 | : this (valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) 69 | { 70 | } 71 | 72 | public Lazy (LazyThreadSafetyMode mode) 73 | : this (Activator.CreateInstance, mode) 74 | { 75 | } 76 | 77 | 78 | 79 | public Lazy (Func valueFactory, LazyThreadSafetyMode mode) 80 | { 81 | if (valueFactory == null) 82 | throw new ArgumentNullException ("valueFactory"); 83 | this.factory = valueFactory; 84 | if (mode != LazyThreadSafetyMode.None) 85 | monitor = new object (); 86 | this.mode = mode; 87 | } 88 | 89 | // Don't trigger expensive initialization 90 | [DebuggerBrowsable (DebuggerBrowsableState.Never)] 91 | public T Value { 92 | get { 93 | if (inited) 94 | return value; 95 | if (exception != null) 96 | throw exception; 97 | 98 | return InitValue (); 99 | } 100 | } 101 | 102 | T InitValue () 103 | { 104 | Func init_factory; 105 | T v; 106 | 107 | switch (mode) { 108 | case LazyThreadSafetyMode.None: 109 | init_factory = factory; 110 | if (init_factory == null) { 111 | if (exception == null) 112 | throw new InvalidOperationException ("The initialization function tries to access Value on this instance"); 113 | throw exception; 114 | } 115 | 116 | try { 117 | factory = null; 118 | v = init_factory (); 119 | value = v; 120 | Thread.MemoryBarrier (); 121 | inited = true; 122 | } catch (Exception ex) { 123 | exception = ex; 124 | throw; 125 | } 126 | break; 127 | 128 | case LazyThreadSafetyMode.PublicationOnly: 129 | init_factory = factory; 130 | 131 | //exceptions are ignored 132 | if (init_factory != null) 133 | v = init_factory (); 134 | else 135 | v = default (T); 136 | 137 | lock (monitor) { 138 | if (inited) 139 | return value; 140 | value = v; 141 | Thread.MemoryBarrier (); 142 | inited = true; 143 | factory = null; 144 | } 145 | break; 146 | 147 | case LazyThreadSafetyMode.ExecutionAndPublication: 148 | lock (monitor) { 149 | if (inited) 150 | return value; 151 | 152 | if (factory == null) { 153 | if (exception == null) 154 | throw new InvalidOperationException ("The initialization function tries to access Value on this instance"); 155 | 156 | throw exception; 157 | } 158 | 159 | init_factory = factory; 160 | try { 161 | factory = null; 162 | v = init_factory (); 163 | value = v; 164 | Thread.MemoryBarrier (); 165 | inited = true; 166 | } catch (Exception ex) { 167 | exception = ex; 168 | throw; 169 | } 170 | } 171 | break; 172 | 173 | default: 174 | throw new InvalidOperationException ("Invalid LazyThreadSafetyMode " + mode); 175 | } 176 | 177 | return value; 178 | } 179 | 180 | public bool IsValueCreated { 181 | get { 182 | return inited; 183 | } 184 | } 185 | 186 | public override string ToString () 187 | { 188 | if (inited) 189 | return value.ToString (); 190 | else 191 | return "Value is not created"; 192 | } 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /System/LazyThreadSafetyMode.cs: -------------------------------------------------------------------------------- 1 | // 2 | // Lazy.cs 3 | // 4 | // Authors: 5 | // Rodrigo Kumpera (kumpera@gmail.com) 6 | // 7 | // Copyright (C) 2010 Novell 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | using System; 30 | 31 | namespace System.Threading 32 | { 33 | public enum LazyThreadSafetyMode 34 | { 35 | None, 36 | PublicationOnly, 37 | ExecutionAndPublication 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /System/LocalDataStoreSlot.cs: -------------------------------------------------------------------------------- 1 | // 2 | // System.LocalDataStoreSlot.cs 3 | // 4 | // Author: 5 | // Dick Porter (dick@ximian.com) 6 | // 7 | // (C) Ximian, Inc. http://www.ximian.com 8 | // 9 | 10 | // 11 | // Copyright (C) 2004 Novell, Inc (http://www.novell.com) 12 | // 13 | // Permission is hereby granted, free of charge, to any person obtaining 14 | // a copy of this software and associated documentation files (the 15 | // "Software"), to deal in the Software without restriction, including 16 | // without limitation the rights to use, copy, modify, merge, publish, 17 | // distribute, sublicense, and/or sell copies of the Software, and to 18 | // permit persons to whom the Software is furnished to do so, subject to 19 | // the following conditions: 20 | // 21 | // The above copyright notice and this permission notice shall be 22 | // included in all copies or substantial portions of the Software. 23 | // 24 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 25 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 26 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 27 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 28 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 29 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 30 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 31 | // 32 | 33 | using System.Reflection; 34 | using System.Runtime.CompilerServices; 35 | using System.Runtime.InteropServices; 36 | 37 | namespace System 38 | { 39 | [ComVisible (true)] 40 | internal sealed class LocalDataStoreSlot 41 | { 42 | internal int slot; 43 | internal bool thread_local; // false for context-local 44 | 45 | static object lock_obj = new object (); 46 | static bool[] slot_bitmap_thread; 47 | static bool[] slot_bitmap_context; 48 | 49 | internal LocalDataStoreSlot (bool in_thread) 50 | { 51 | thread_local = in_thread; 52 | lock (lock_obj) { 53 | int i; 54 | bool[] slot_bitmap; 55 | if (in_thread) 56 | slot_bitmap = slot_bitmap_thread; 57 | else 58 | slot_bitmap = slot_bitmap_context; 59 | if (slot_bitmap != null) { 60 | for (i = 0; i < slot_bitmap.Length; ++i) { 61 | if (!slot_bitmap [i]) { 62 | slot = i; 63 | slot_bitmap [i] = true; 64 | return; 65 | } 66 | } 67 | bool[] new_bitmap = new bool [i + 2]; 68 | slot_bitmap.CopyTo (new_bitmap, 0); 69 | slot_bitmap = new_bitmap; 70 | } else { 71 | slot_bitmap = new bool [2]; 72 | i = 0; 73 | } 74 | slot_bitmap [i] = true; 75 | slot = i; 76 | if (in_thread) 77 | slot_bitmap_thread = slot_bitmap; 78 | else 79 | slot_bitmap_context = slot_bitmap; 80 | } 81 | } 82 | 83 | ~LocalDataStoreSlot () 84 | { 85 | /* first remove all the values from the slots and 86 | * then free the slot itself for reuse. 87 | */ 88 | //System.Threading.Thread.FreeLocalSlotValues (slot, thread_local); 89 | lock (lock_obj) { 90 | if (thread_local) 91 | slot_bitmap_thread [slot] = false; 92 | else 93 | slot_bitmap_context [slot] = false; 94 | } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /System/OperationCanceledException.cs: -------------------------------------------------------------------------------- 1 | // 2 | // System.OperationCanceledException.cs 3 | // 4 | // Authors: 5 | // Zoltan Varga 6 | // Jérémie Laval 7 | // 8 | // Copyright (C) 2004 Novell, Inc (http://www.novell.com) 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining 11 | // a copy of this software and associated documentation files (the 12 | // "Software"), to deal in the Software without restriction, including 13 | // without limitation the rights to use, copy, modify, merge, publish, 14 | // distribute, sublicense, and/or sell copies of the Software, and to 15 | // permit persons to whom the Software is furnished to do so, subject to 16 | // the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | using System.Runtime.Serialization; 31 | using System.Runtime.InteropServices; 32 | using System.Threading; 33 | 34 | namespace System.Couchbase 35 | { 36 | [Serializable] 37 | [ComVisible (true)] 38 | public class OperationCanceledException : System.OperationCanceledException 39 | { 40 | 41 | const int Result = unchecked ((int)0x8013153b); 42 | readonly CancellationToken? token; 43 | 44 | // Constructors 45 | public OperationCanceledException () 46 | : base ("The operation was canceled.") 47 | { 48 | } 49 | 50 | public OperationCanceledException (string message) 51 | : base (message) 52 | { 53 | } 54 | 55 | public OperationCanceledException (string message, Exception innerException) 56 | : base (message, innerException) 57 | { 58 | } 59 | 60 | protected OperationCanceledException (SerializationInfo info, StreamingContext context) 61 | : base (info, context) 62 | { 63 | } 64 | 65 | public OperationCanceledException (CancellationToken token) 66 | : this () 67 | { 68 | this.token = token; 69 | } 70 | 71 | public OperationCanceledException (string message, CancellationToken token) 72 | : this (message) 73 | { 74 | this.token = token; 75 | } 76 | 77 | public OperationCanceledException (string message, Exception innerException, CancellationToken token) 78 | : base (message, innerException) 79 | { 80 | this.token = token; 81 | } 82 | 83 | public CancellationToken CancellationToken { 84 | get { 85 | if (token == null) 86 | return CancellationToken.None; 87 | return token.Value; 88 | } 89 | } 90 | 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /System/Tuple.cs: -------------------------------------------------------------------------------- 1 | // 2 | // Tuple.cs 3 | // 4 | // Authors: 5 | // Zoltan Varga (vargaz@gmail.com) 6 | // 7 | // Copyright (C) 2009 Novell 8 | // 9 | // Permission is hereby granted, free of charge, to any person obtaining 10 | // a copy of this software and associated documentation files (the 11 | // "Software"), to deal in the Software without restriction, including 12 | // without limitation the rights to use, copy, modify, merge, publish, 13 | // distribute, sublicense, and/or sell copies of the Software, and to 14 | // permit persons to whom the Software is furnished to do so, subject to 15 | // the following conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 25 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 26 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 27 | // 28 | 29 | using System; 30 | 31 | namespace System 32 | { 33 | public static class Tuple 34 | { 35 | public static Tuple> Create 36 | ( 37 | T1 item1, 38 | T2 item2, 39 | T3 item3, 40 | T4 item4, 41 | T5 item5, 42 | T6 item6, 43 | T7 item7, 44 | T8 item8) { 45 | return new Tuple> (item1, item2, item3, item4, item5, item6, item7, new Tuple (item8)); 46 | } 47 | 48 | public static Tuple Create 49 | ( 50 | T1 item1, 51 | T2 item2, 52 | T3 item3, 53 | T4 item4, 54 | T5 item5, 55 | T6 item6, 56 | T7 item7) { 57 | return new Tuple (item1, item2, item3, item4, item5, item6, item7); 58 | } 59 | 60 | public static Tuple Create 61 | ( 62 | T1 item1, 63 | T2 item2, 64 | T3 item3, 65 | T4 item4, 66 | T5 item5, 67 | T6 item6) { 68 | return new Tuple (item1, item2, item3, item4, item5, item6); 69 | } 70 | 71 | public static Tuple Create 72 | ( 73 | T1 item1, 74 | T2 item2, 75 | T3 item3, 76 | T4 item4, 77 | T5 item5) { 78 | return new Tuple (item1, item2, item3, item4, item5); 79 | } 80 | 81 | public static Tuple Create 82 | ( 83 | T1 item1, 84 | T2 item2, 85 | T3 item3, 86 | T4 item4) { 87 | return new Tuple (item1, item2, item3, item4); 88 | } 89 | 90 | public static Tuple Create 91 | ( 92 | T1 item1, 93 | T2 item2, 94 | T3 item3) { 95 | return new Tuple (item1, item2, item3); 96 | } 97 | 98 | public static Tuple Create 99 | ( 100 | T1 item1, 101 | T2 item2) { 102 | return new Tuple (item1, item2); 103 | } 104 | 105 | public static Tuple Create 106 | ( 107 | T1 item1) { 108 | return new Tuple (item1); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /UnityExt.cs: -------------------------------------------------------------------------------- 1 | // 2 | // UnityExt.cs 3 | // 4 | // Author: 5 | // Jim Borden 6 | // 7 | // Copyright (c) 2015 Couchbase, Inc All rights reserved. 8 | // 9 | // Licensed under the Apache License, Version 2.0 (the "License"); 10 | // you may not use this file except in compliance with the License. 11 | // You may obtain a copy of the License at 12 | // 13 | // http://www.apache.org/licenses/LICENSE-2.0 14 | // 15 | // Unless required by applicable law or agreed to in writing, software 16 | // distributed under the License is distributed on an "AS IS" BASIS, 17 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | // See the License for the specific language governing permissions and 19 | // limitations under the License. 20 | // 21 | //#if UNITY 22 | using System.Threading.Tasks; 23 | using System.Threading; 24 | 25 | namespace System 26 | { 27 | internal static class UnityExt 28 | { 29 | public static T Await(this Task t) 30 | { 31 | using(var mre = new ManualResetEventSlim()) { 32 | t.ConfigureAwait(false).GetAwaiter().OnCompleted(mre.Set); 33 | mre.Wait(); 34 | return t.Result; 35 | } 36 | } 37 | 38 | public static void Await(this Task t) 39 | { 40 | using(var mre = new ManualResetEventSlim()) { 41 | t.ConfigureAwait(false).GetAwaiter().OnCompleted(mre.Set); 42 | mre.Wait(); 43 | } 44 | } 45 | } 46 | } 47 | //#endif --------------------------------------------------------------------------------