File: ConcurrentBag.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1121 lines) | stat: -rw-r--r-- 40,451 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
// 
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ConcurrentBag.cs
//
// <OWNER>Microsoft</OWNER>
//
// 
//An unordered collection that allows duplicates and that provides add and get operations.
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Security.Permissions;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;

namespace System.Collections.Concurrent
{
    /// <summary>
    /// Represents an thread-safe, unordered collection of objects. 
    /// </summary>
    /// <typeparam name="T">Specifies the type of elements in the bag.</typeparam>
    /// <remarks>
    /// <para>
    /// Bags are useful for storing objects when ordering doesn't matter, and unlike sets, bags support
    /// duplicates. <see cref="ConcurrentBag{T}"/> is a thread-safe bag implementation, optimized for
    /// scenarios where the same thread will be both producing and consuming data stored in the bag.
    /// </para>
    /// <para>
    /// <see cref="ConcurrentBag{T}"/> accepts null reference (Nothing in Visual Basic) as a valid 
    /// value for reference types.
    /// </para>
    /// <para>
    /// All public and protected members of <see cref="ConcurrentBag{T}"/> are thread-safe and may be used
    /// concurrently from multiple threads.
    /// </para>
    /// </remarks>
#if !SILVERLIGHT
    [Serializable]
#endif
    [ComVisible(false)]
    [DebuggerTypeProxy(typeof(SystemThreadingCollection_IProducerConsumerCollectionDebugView<>))]
    [DebuggerDisplay("Count = {Count}")]
#if !FEATURE_NETCORE
    [HostProtection(Synchronization = true, ExternalThreading = true)]
#endif
    public class ConcurrentBag<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
    {

        // ThreadLocalList object that contains the data per thread
#if !SILVERLIGHT
        [NonSerialized]
#endif
        ThreadLocal<ThreadLocalList> m_locals;

        // This head and tail pointers points to the first and last local lists, to allow enumeration on the thread locals objects
#if !SILVERLIGHT
        [NonSerialized]
#endif
        volatile ThreadLocalList m_headList, m_tailList;

        // A flag used to tell the operations thread that it must synchronize the operation, this flag is set/unset within
        // GlobalListsLock lock
#if !SILVERLIGHT
        [NonSerialized]
#endif
        bool m_needSync;

#if !SILVERLIGHT
        // Used for custom serialization.
        private T[] m_serializationArray;
#endif

        /// <summary>
        /// Initializes a new instance of the <see cref="ConcurrentBag{T}"/>
        /// class.
        /// </summary>
        public ConcurrentBag()
        {
            Initialize(null);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConcurrentBag{T}"/>
        /// class that contains elements copied from the specified collection.
        /// </summary>
        /// <param name="collection">The collection whose elements are copied to the new <see
        /// cref="ConcurrentBag{T}"/>.</param>
        /// <exception cref="ArgumentNullException"><paramref name="collection"/> is a null reference
        /// (Nothing in Visual Basic).</exception>
        public ConcurrentBag(IEnumerable<T> collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection", SR.GetString(SR.ConcurrentBag_Ctor_ArgumentNullException));
            }
            Initialize(collection);
        }


        /// <summary>
        /// Local helper function to initalize a new bag object
        /// </summary>
        /// <param name="collection">An enumeration containing items with which to initialize this bag.</param>
        private void Initialize(IEnumerable<T> collection)
        {
            m_locals = new ThreadLocal<ThreadLocalList>();

            // Copy the collection to the bag
            if (collection != null)
            {
                ThreadLocalList list = GetThreadList(true);
                foreach (T item in collection)
                {
                    list.Add(item, false);
                }
            }
        }

        /// <summary>
        /// Adds an object to the <see cref="ConcurrentBag{T}"/>.
        /// </summary>
        /// <param name="item">The object to be added to the
        /// <see cref="ConcurrentBag{T}"/>. The value can be a null reference
        /// (Nothing in Visual Basic) for reference types.</param>
        public void Add(T item)
        {
            // Get the local list for that thread, create a new list if this thread doesn't exist 
            //(first time to call add)
            ThreadLocalList list = GetThreadList(true);
            AddInternal(list, item);
        }

        /// <summary>
        /// </summary>
        /// <param name="list"></param>
        /// <param name="item"></param>
        private void AddInternal(ThreadLocalList list, T item)
        {
            bool lockTaken = false;
            try
            {
#pragma warning disable 0420
                Interlocked.Exchange(ref list.m_currentOp, (int)ListOperation.Add);
#pragma warning restore 0420
                //Synchronization cases:
                // if the list count is less than two to avoid conflict with any stealing thread
                // if m_needSync is set, this means there is a thread that needs to freeze the bag
                if (list.Count < 2 || m_needSync)
                {
                    // reset it back to zero to avoid deadlock with stealing thread
                    list.m_currentOp = (int)ListOperation.None;
                    Monitor.Enter(list, ref lockTaken);
                }
                list.Add(item, lockTaken);
            }
            finally
            {
                list.m_currentOp = (int)ListOperation.None;
                if (lockTaken)
                {
                    Monitor.Exit(list);
                }
            }
        }

        /// <summary>
        /// Attempts to add an object to the <see cref="ConcurrentBag{T}"/>.
        /// </summary>
        /// <param name="item">The object to be added to the 
        /// <see cref="ConcurrentBag{T}"/>. The value can be a null reference
        /// (Nothing in Visual Basic) for reference types.</param>
        /// <returns>Always returns true</returns>
        bool IProducerConsumerCollection<T>.TryAdd(T item)
        {
            Add(item);
            return true;
        }

        /// <summary>
        /// Attempts to remove and return an object from the <see
        /// cref="ConcurrentBag{T}"/>.
        /// </summary>
        /// <param name="result">When this method returns, <paramref name="result"/> contains the object
        /// removed from the <see cref="ConcurrentBag{T}"/> or the default value
        /// of <typeparamref name="T"/> if the operation failed.</param>
        /// <returns>true if an object was removed successfully; otherwise, false.</returns>
        public bool TryTake(out T result)
        {
            return TryTakeOrPeek(out result, true);
        }

        /// <summary>
        /// Attempts to return an object from the <see cref="ConcurrentBag{T}"/>
        /// without removing it.
        /// </summary>
        /// <param name="result">When this method returns, <paramref name="result"/> contains an object from
        /// the <see cref="ConcurrentBag{T}"/> or the default value of
        /// <typeparamref name="T"/> if the operation failed.</param>
        /// <returns>true if and object was returned successfully; otherwise, false.</returns>
        public bool TryPeek(out T result)
        {
            return TryTakeOrPeek(out result, false);
        }

        /// <summary>
        /// Local helper function to Take or Peek an item from the bag
        /// </summary>
        /// <param name="result">To receive the item retrieved from the bag</param>
        /// <param name="take">True means Take operation, false means Peek operation</param>
        /// <returns>True if succeeded, false otherwise</returns>
        private bool TryTakeOrPeek(out T result, bool take)
        {

            // Get the local list for that thread, return null if the thread doesn't exit 
            //(this thread never add before) 
            ThreadLocalList list = GetThreadList(false);
            if (list == null || list.Count == 0)
            {
                return Steal(out result, take);
            }

            bool lockTaken = false;
            try
            {
                if (take) // Take operation
                {
#pragma warning disable 0420
                    Interlocked.Exchange(ref list.m_currentOp, (int)ListOperation.Take);
#pragma warning restore 0420
                    //Synchronization cases:
                    // if the list count is less than or equal two to avoid conflict with any stealing thread
                    // if m_needSync is set, this means there is a thread that needs to freeze the bag
                    if (list.Count <= 2 || m_needSync)
                    {
                        // reset it back to zero to avoid deadlock with stealing thread
                        list.m_currentOp = (int)ListOperation.None;
                        Monitor.Enter(list, ref lockTaken);

                        // Double check the count and steal if it became empty
                        if (list.Count == 0)
                        {
                            // Release the lock before stealing
                            if (lockTaken)
                            {
                                try { }
                                finally
                                {
                                    lockTaken = false; // reset lockTaken to avoid calling Monitor.Exit again in the finally block
                                    Monitor.Exit(list);
                                }
                            }
                            return Steal(out result, true);
                        }
                    }
                    list.Remove(out result);
                }
                else
                {
                    if (!list.Peek(out result))
                    {
                        return Steal(out result, false);
                    }
                }
            }
            finally
            {
                list.m_currentOp = (int)ListOperation.None;
                if (lockTaken)
                {
                    Monitor.Exit(list);
                }
            }
            return true;
        }


        /// <summary>
        /// Local helper function to retrieve a thread local list by a thread object
        /// </summary>
        /// <param name="forceCreate">Create a new list if the thread does ot exist</param>
        /// <returns>The local list object</returns>
        private ThreadLocalList GetThreadList(bool forceCreate)
        {
            ThreadLocalList list = m_locals.Value;

            if (list != null)
            {
                return list;
            }
            else if (forceCreate)
            {
                // Acquire the lock to update the m_tailList pointer
                lock (GlobalListsLock)
                {
                    if (m_headList == null)
                    {
                        list = new ThreadLocalList(Thread.CurrentThread);
                        m_headList = list;
                        m_tailList = list;
                    }
                    else
                    {

                        list = GetUnownedList();
                        if (list == null)
                        {
                            list = new ThreadLocalList(Thread.CurrentThread);
                            m_tailList.m_nextList = list;
                            m_tailList = list;
                        }
                    }
                    m_locals.Value = list;
                }
            }
            else
            {
                return null;
            }
            Debug.Assert(list != null);
            return list;

        }

        /// <summary>
        /// Try to reuse an unowned list if exist
        /// unowned lists are the lists that their owner threads are aborted or terminated
        /// this is workaround to avoid memory leaks.
        /// </summary>
        /// <returns>The list object, null if all lists are owned</returns>
        private ThreadLocalList GetUnownedList()
        {
            //the global lock must be held at this point
            Contract.Assert(Monitor.IsEntered(GlobalListsLock));

            ThreadLocalList currentList = m_headList;
            while (currentList != null)
            {
                if (currentList.m_ownerThread.ThreadState == System.Threading.ThreadState.Stopped)
                {
                    currentList.m_ownerThread = Thread.CurrentThread; // the caller should acquire a lock to make this line thread safe
                    return currentList;
                }
                currentList = currentList.m_nextList;
            }
            return null;
        }


        /// <summary>
        /// Local helper method to steal an item from any other non empty thread
        /// It enumerate all other threads in two passes first pass acquire the lock with TryEnter if succeeded
        /// it steals the item, otherwise it enumerate them again in 2nd pass and acquire the lock using Enter
        /// </summary>
        /// <param name="result">To receive the item retrieved from the bag</param>
        /// <param name="take">Whether to remove or peek.</param>
        /// <returns>True if succeeded, false otherwise.</returns>
        private bool Steal(out T result, bool take)
        {
#if !FEATURE_PAL && !SILVERLIGHT    // PAL doesn't support  eventing
            if (take)
                CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryTakeSteals();
            else
                CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryPeekSteals();
#endif

            bool loop;
            List<int> versionsList = new List<int>(); // save the lists version
            do
            {
                versionsList.Clear(); //clear the list from the previous iteration
                loop = false;
              

                ThreadLocalList currentList = m_headList;
                while (currentList != null)
                {
                    versionsList.Add(currentList.m_version);
                    if (currentList.m_head != null && TrySteal(currentList, out result, take))
                    {
                        return true;
                    }
                    currentList = currentList.m_nextList;
                }

                // verify versioning, if other items are added to this list since we last visit it, we should retry
                currentList = m_headList;
                foreach (int version in versionsList)
                {
                    if (version != currentList.m_version) //oops state changed
                    {
                        loop = true;
                        if (currentList.m_head != null && TrySteal(currentList, out result, take))
                            return true;
                    }
                    currentList = currentList.m_nextList;
                }
            } while (loop);


            result = default(T);
            return false;
        }

        /// <summary>
        /// local helper function tries to steal an item from given local list
        /// </summary>
        private bool TrySteal(ThreadLocalList list, out T result, bool take)
        {
            lock (list)
            {
                if (CanSteal(list))
                {
                    list.Steal(out result, take);
                    return true;
                }
                result = default(T);
                return false;
            }

        }
        /// <summary>
        /// Local helper function to check the list if it became empty after acquiring the lock
        /// and wait if there is unsynchronized Add/Take operation in the list to be done
        /// </summary>
        /// <param name="list">The list to steal</param>
        /// <returns>True if can steal, false otherwise</returns>
        private bool CanSteal(ThreadLocalList list)
        {
            if (list.Count <= 2 && list.m_currentOp != (int)ListOperation.None)
            {
                SpinWait spinner = new SpinWait();
                while (list.m_currentOp != (int)ListOperation.None)
                {
                    spinner.SpinOnce();
                }
            }
            if (list.Count > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// Copies the <see cref="ConcurrentBag{T}"/> elements to an existing
        /// one-dimensional <see cref="T:System.Array">Array</see>, starting at the specified array
        /// index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
        /// destination of the elements copied from the
        /// <see cref="ConcurrentBag{T}"/>. The <see
        /// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
        /// <param name="index">The zero-based index in <paramref name="array"/> at which copying
        /// begins.</param>
        /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
        /// Visual Basic).</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
        /// zero.</exception>
        /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
        /// length of the <paramref name="array"/>
        /// -or- the number of elements in the source <see
        /// cref="ConcurrentBag{T}"/> is greater than the available space from
        /// <paramref name="index"/> to the end of the destination <paramref name="array"/>.</exception>
        public void CopyTo(T[] array, int index)
        {
            if (array == null)
            {
                throw new ArgumentNullException("array", SR.GetString(SR.ConcurrentBag_CopyTo_ArgumentNullException));
            }
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException
                    ("index", SR.GetString(SR.ConcurrentBag_CopyTo_ArgumentOutOfRangeException));
            }

            // Short path if the bag is empty
            if (m_headList == null)
                return;

            bool lockTaken = false;
            try
            {
                FreezeBag(ref lockTaken);
                ToList().CopyTo(array, index);
            }
            finally
            {
                UnfreezeBag(lockTaken);
            }
        }

        /// <summary>
        /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
        /// cref="T:System.Array"/>, starting at a particular
        /// <see cref="T:System.Array"/> index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
        /// destination of the elements copied from the
        /// <see cref="ConcurrentBag{T}"/>. The <see
        /// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
        /// <param name="index">The zero-based index in <paramref name="array"/> at which copying
        /// begins.</param>
        /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
        /// Visual Basic).</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
        /// zero.</exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="array"/> is multidimensional. -or-
        /// <paramref name="array"/> does not have zero-based indexing. -or-
        /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
        /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is
        /// greater than the available space from <paramref name="index"/> to the end of the destination
        /// <paramref name="array"/>. -or- The type of the source <see
        /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the
        /// destination <paramref name="array"/>.
        /// </exception>
        void ICollection.CopyTo(Array array, int index)
        {
            if (array == null)
            {
                throw new ArgumentNullException("array", SR.GetString(SR.ConcurrentBag_CopyTo_ArgumentNullException));
            }

            bool lockTaken = false;
            try
            {
                FreezeBag(ref lockTaken);
                ((ICollection)ToList()).CopyTo(array, index);
            }
            finally
            {
                UnfreezeBag(lockTaken);
            }

        }


        /// <summary>
        /// Copies the <see cref="ConcurrentBag{T}"/> elements to a new array.
        /// </summary>
        /// <returns>A new array containing a snapshot of elements copied from the <see
        /// cref="ConcurrentBag{T}"/>.</returns>
        public T[] ToArray()
        {
            // Short path if the bag is empty
            if (m_headList == null)
                return new T[0];

            bool lockTaken = false;
            try
            {
                FreezeBag(ref lockTaken);
                return ToList().ToArray();
            }
            finally
            {
                UnfreezeBag(lockTaken);
            }
        }

        /// <summary>
        /// Returns an enumerator that iterates through the <see
        /// cref="ConcurrentBag{T}"/>.
        /// </summary>
        /// <returns>An enumerator for the contents of the <see
        /// cref="ConcurrentBag{T}"/>.</returns>
        /// <remarks>
        /// The enumeration represents a moment-in-time snapshot of the contents
        /// of the bag.  It does not reflect any updates to the collection after 
        /// <see cref="GetEnumerator"/> was called.  The enumerator is safe to use
        /// concurrently with reads from and writes to the bag.
        /// </remarks>
        public IEnumerator<T> GetEnumerator()
        {
            // Short path if the bag is empty
            if (m_headList == null)
                return new List<T>().GetEnumerator(); // empty list

            bool lockTaken = false;
            try
            {
                FreezeBag(ref lockTaken);
                return ToList().GetEnumerator();
            }
            finally
            {
                UnfreezeBag(lockTaken);
            }
        }

        /// <summary>
        /// Returns an enumerator that iterates through the <see
        /// cref="ConcurrentBag{T}"/>.
        /// </summary>
        /// <returns>An enumerator for the contents of the <see
        /// cref="ConcurrentBag{T}"/>.</returns>
        /// <remarks>
        /// The items enumerated represent a moment-in-time snapshot of the contents
        /// of the bag.  It does not reflect any update to the collection after 
        /// <see cref="GetEnumerator"/> was called.
        /// </remarks>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((ConcurrentBag<T>)this).GetEnumerator();
        }
#if !SILVERLIGHT
        /// <summary>
        /// Get the data array to be serialized
        /// </summary>
        [OnSerializing]
        private void OnSerializing(StreamingContext context)
        {
            // save the data into the serialization array to be saved
            m_serializationArray = ToArray();
        }

        /// <summary>
        /// Construct the stack from a previously seiralized one
        /// </summary>
        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            m_locals = new ThreadLocal<ThreadLocalList>();

            ThreadLocalList list = GetThreadList(true);
            foreach (T item in m_serializationArray)
            {
                list.Add(item, false);
            }
            m_headList = list;
            m_tailList = list;

            m_serializationArray = null;
        }
#endif
        /// <summary>
        /// Gets the number of elements contained in the <see cref="ConcurrentBag{T}"/>.
        /// </summary>
        /// <value>The number of elements contained in the <see cref="ConcurrentBag{T}"/>.</value>
        /// <remarks>
        /// The count returned represents a moment-in-time snapshot of the contents
        /// of the bag.  It does not reflect any updates to the collection after 
        /// <see cref="GetEnumerator"/> was called.
        /// </remarks>
        public int Count
        {
            get
            {
                // Short path if the bag is empty
                if (m_headList == null)
                    return 0;

                bool lockTaken = false;
                try
                {
                    FreezeBag(ref lockTaken);
                    return GetCountInternal();
                }
                finally
                {
                    UnfreezeBag(lockTaken);
                }
            }
        }

        /// <summary>
        /// Gets a value that indicates whether the <see cref="ConcurrentBag{T}"/> is empty.
        /// </summary>
        /// <value>true if the <see cref="ConcurrentBag{T}"/> is empty; otherwise, false.</value>
        public bool IsEmpty
        {
            get
            {
                if (m_headList == null)
                    return true;

                bool lockTaken = false;
                try
                {
                    FreezeBag(ref lockTaken);
                    ThreadLocalList currentList = m_headList;
                    while (currentList != null)
                    {
                        if (currentList.m_head != null)
                            //at least this list is not empty, we return false
                        {
                            return false;
                        }
                        currentList = currentList.m_nextList;
                    }
                    return true;
                }
                finally
                {
                    UnfreezeBag(lockTaken);
                }
            }
        }

        /// <summary>
        /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
        /// synchronized with the SyncRoot.
        /// </summary>
        /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
        /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentBag{T}"/>, this property always
        /// returns false.</value>
        bool ICollection.IsSynchronized
        {
            get { return false; }
        }

        /// <summary>
        /// Gets an object that can be used to synchronize access to the <see
        /// cref="T:System.Collections.ICollection"/>. This property is not supported.
        /// </summary>
        /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception>
        object ICollection.SyncRoot
        {
            get
            {
                throw new NotSupportedException(SR.GetString(SR.ConcurrentCollection_SyncRoot_NotSupported));
            }
        }


        /// <summary>
        ///  A global lock object, used in two cases:
        ///  1- To  maintain the m_tailList pointer for each new list addition process ( first time a thread called Add )
        ///  2- To freeze the bag in GetEnumerator, CopyTo, ToArray and Count members
        /// </summary>
        private object GlobalListsLock
        {
            get 
            {
                Contract.Assert(m_locals != null);
                return m_locals; 
            }
        }


        #region Freeze bag helper methods
        /// <summary>
        /// Local helper method to freeze all bag operations, it
        /// 1- Acquire the global lock to prevent any other thread to freeze the bag, and also new new thread can be added
        /// to the dictionary
        /// 2- Then Acquire all local lists locks to prevent steal and synchronized operations
        /// 3- Wait for all un-synchronized operations to be done
        /// </summary>
        /// <param name="lockTaken">Retrieve the lock taken result for the global lock, to be passed to Unfreeze method</param>
        private void FreezeBag(ref bool lockTaken)
        {
            Contract.Assert(!Monitor.IsEntered(GlobalListsLock));

            // global lock to be safe against multi threads calls count and corrupt m_needSync
            Monitor.Enter(GlobalListsLock, ref lockTaken);

            // This will force any future add/take operation to be synchronized
            m_needSync = true;

            //Acquire all local lists locks
            AcquireAllLocks();

            // Wait for all un-synchronized operation to be done
            WaitAllOperations();
        }

        /// <summary>
        /// Local helper method to unfreeze the bag from a frozen state
        /// </summary>
        /// <param name="lockTaken">The lock taken result from the Freeze method</param>
        private void UnfreezeBag(bool lockTaken)
        {
            ReleaseAllLocks();
            m_needSync = false;
            if (lockTaken)
            {
                Monitor.Exit(GlobalListsLock);
            }
        }

        /// <summary>
        /// local helper method to acquire all local lists locks
        /// </summary>
        private void AcquireAllLocks()
        {
            Contract.Assert(Monitor.IsEntered(GlobalListsLock));

            bool lockTaken = false;
            ThreadLocalList currentList = m_headList;
            while (currentList != null)
            {
                // Try/Finally bllock to avoid thread aport between acquiring the lock and setting the taken flag
                try
                {
                    Monitor.Enter(currentList, ref lockTaken);
                }
                finally
                {
                    if (lockTaken)
                    {
                        currentList.m_lockTaken = true;
                        lockTaken = false;
                    }
                }
                currentList = currentList.m_nextList;
            }
        }

        /// <summary>
        /// Local helper method to release all local lists locks
        /// </summary>
        private void ReleaseAllLocks()
        {
            ThreadLocalList currentList = m_headList;
            while (currentList != null)
            {

                if (currentList.m_lockTaken)
                {
                    currentList.m_lockTaken = false;
                    Monitor.Exit(currentList);
                }
                currentList = currentList.m_nextList;
            }
        }

        /// <summary>
        /// Local helper function to wait all unsynchronized operations
        /// </summary>
        private void WaitAllOperations()
        {
            Contract.Assert(Monitor.IsEntered(GlobalListsLock));

            ThreadLocalList currentList = m_headList;
            while (currentList != null)
            {
                if (currentList.m_currentOp != (int)ListOperation.None)
                {
                    SpinWait spinner = new SpinWait();
                    while (currentList.m_currentOp != (int)ListOperation.None)
                    {
                        spinner.SpinOnce();
                    }
                }
                currentList = currentList.m_nextList;
            }
        }

        /// <summary>
        /// Local helper function to get the bag count, the caller should call it from Freeze/Unfreeze block
        /// </summary>
        /// <returns>The current bag count</returns>
        private int GetCountInternal()
        {
            Contract.Assert(Monitor.IsEntered(GlobalListsLock));

            int count = 0;
            ThreadLocalList currentList = m_headList;
            while (currentList != null)
            {
                checked
                {
                    count += currentList.Count;
                }
                currentList = currentList.m_nextList;
            }
            return count;
        }

        /// <summary>
        /// Local helper function to return the bag item in a list, this is mainly used by CopyTo and ToArray
        /// This is not thread safe, should be called in Freeze/UnFreeze bag block
        /// </summary>
        /// <returns>List the contains the bag items</returns>
        private List<T> ToList()
        {
            Contract.Assert(Monitor.IsEntered(GlobalListsLock));

            List<T> list = new List<T>();
            ThreadLocalList currentList = m_headList;
            while (currentList != null)
            {
                Node currentNode = currentList.m_head;
                while (currentNode != null)
                {
                    list.Add(currentNode.m_value);
                    currentNode = currentNode.m_next;
                }
                currentList = currentList.m_nextList;
            }

            return list;
        }

        #endregion


        #region Inner Classes

        /// <summary>
        /// A class that represents a node in the lock thread list
        /// </summary>
#if !SILVERLIGHT
        [Serializable]
#endif
        internal class Node
        {
            public Node(T value)
            {
                m_value = value;
            }
            public readonly T m_value;
            public Node m_next;
            public Node m_prev;
        }

        /// <summary>
        /// A class that represents the lock thread list
        /// </summary>
        internal class ThreadLocalList
        {
            // Tead node in the list, null means the list is empty
            internal volatile Node m_head;

            // Tail node for the list
            private volatile Node m_tail;

            // The current list operation
            internal volatile int m_currentOp;

            // The list count from the Add/Take prespective
            private int m_count;

            // The stealing count
            internal int m_stealCount;

            // Next list in the dictionary values
            internal volatile ThreadLocalList m_nextList;

            // Set if the locl lock is taken
            internal bool m_lockTaken;

            // The owner thread for this list
            internal Thread m_ownerThread;

            // the version of the list, incremented only when the list changed from empty to non empty state
            internal volatile int m_version;

            /// <summary>
            /// ThreadLocalList constructor
            /// </summary>
            /// <param name="ownerThread">The owner thread for this list</param>
            internal ThreadLocalList(Thread ownerThread)
            {
                m_ownerThread = ownerThread;
            }
            /// <summary>
            /// Add new item to head of the list
            /// </summary>
            /// <param name="item">The item to add.</param>
            /// <param name="updateCount">Whether to update the count.</param>
            internal void Add(T item, bool updateCount)
            {
                checked
                {
                    m_count++;
                }
                Node node = new Node(item);
                if (m_head == null)
                {
                    Debug.Assert(m_tail == null);
                    m_head = node;
                    m_tail = node;
                    m_version++; // changing from empty state to non empty state
                }
                else
                {
                    node.m_next = m_head;
                    m_head.m_prev = node;
                    m_head = node;
                }
                if (updateCount) // update the count to avoid overflow if this add is synchronized
                {
                    m_count = m_count - m_stealCount;
                    m_stealCount = 0;
                }
            }

            /// <summary>
            /// Remove an item from the head of the list
            /// </summary>
            /// <param name="result">The removed item</param>
            internal void Remove(out T result)
            {
                Debug.Assert(m_head != null);
                Node head = m_head;
                m_head = m_head.m_next;
                if (m_head != null)
                {
                    m_head.m_prev = null;
                }
                else
                {
                    m_tail = null;
                }
                m_count--;
                result = head.m_value;

            }

            /// <summary>
            /// Peek an item from the head of the list
            /// </summary>
            /// <param name="result">the peeked item</param>
            /// <returns>True if succeeded, false otherwise</returns>
            internal bool Peek(out T result)
            {
                Node head = m_head;
                if (head != null)
                {
                    result = head.m_value;
                    return true;
                }
                result = default(T);
                return false;
            }

            /// <summary>
            /// Steal an item from the tail of the list
            /// </summary>
            /// <param name="result">the removed item</param>
            /// <param name="remove">remove or peek flag</param>
            internal void Steal(out T result, bool remove)
            {
                Node tail = m_tail;
                Debug.Assert(tail != null);
                if (remove) // Take operation
                {
                    m_tail = m_tail.m_prev;
                    if (m_tail != null)
                    {
                        m_tail.m_next = null;
                    }
                    else
                    {
                        m_head = null;
                    }
                    // Increment the steal count
                    m_stealCount++;
                }
                result = tail.m_value;
            }


            /// <summary>
            /// Gets the total list count, it's not thread safe, may provide incorrect count if it is called concurrently
            /// </summary>
            internal int Count
            {
                get
                {
                    return m_count - m_stealCount;
                }
            }
        }

        /// <summary>
        /// List operations
        /// </summary>
        internal enum ListOperation
        {
            None,
            Add,
            Take
        };
        #endregion
    }


    #region Internal Types

    /// <summary>
    /// A simple class for the debugger view window
    /// </summary>
    internal sealed class SystemThreadingCollection_IProducerConsumerCollectionDebugView<T>
    {
        IProducerConsumerCollection<T> m_collection;
        public SystemThreadingCollection_IProducerConsumerCollectionDebugView(IProducerConsumerCollection<T> collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }
            m_collection = collection;
        }

        /// <summary>
        /// Returns a snapshot of the underlying collection's elements.
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
        public T[] Items
        {
            get { return m_collection.ToArray(); }
        }
    }

    #endregion

}