Ejemplo n.º 1
0
        public static void GetEnumerator_EnumerationsAreSnapshots()
        {
            var bag = new ConcurrentBag <int>();

            Assert.Empty(bag);

            using (IEnumerator <int> e1 = bag.GetEnumerator())
            {
                bag.Add(1);
                using (IEnumerator <int> e2 = bag.GetEnumerator())
                {
                    bag.Add(2);
                    using (IEnumerator <int> e3 = bag.GetEnumerator())
                    {
                        int item;
                        Assert.True(bag.TryTake(out item));
                        using (IEnumerator <int> e4 = bag.GetEnumerator())
                        {
                            Assert.False(e1.MoveNext());

                            Assert.True(e2.MoveNext());
                            Assert.False(e2.MoveNext());

                            Assert.True(e3.MoveNext());
                            Assert.True(e3.MoveNext());
                            Assert.False(e3.MoveNext());

                            Assert.True(e4.MoveNext());
                            Assert.False(e4.MoveNext());
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public virtual async Task EnqueueMultipleItemsSucceeds()
        {
            // Arrange
            var queue = Create();
            var items = new ConcurrentBag <T>();
            var count = 100;

            for (int i = 0; i < count; i++)
            {
                var item = Fixture.Create <T>();
                items.Add(item);
            }

            // Act
            var enumerator = items.GetEnumerator();
            var tasks      = Enumerable
                             .Range(0, count)
                             .Where(i => enumerator.MoveNext())
                             .Select(i => Task.Run(async() => await queue.EnqueueAsync(enumerator.Current)));

            await Task.WhenAll(tasks);

            // Assert
            AssertEquals(await queue.GetLengthAsync(), count);
            while (await queue.GetLengthAsync() > 0)
            {
                var item = await queue.DequeueOrDefaultAsync();

                AssertIsTrue(items.Contains(item));
            }
            AssertEquals(await queue.GetLengthAsync(), 0);
        }
 /// <summary>
 ///     Returns an enumerator that iterates through the <see cref="SocketAwaitablePool" />.
 /// </summary>
 /// <returns>
 ///     An enumerator for the contents of the <see cref="SocketAwaitablePool" />.
 /// </returns>
 /// <exception cref="ObjectDisposedException">
 ///     The <see cref="SocketAwaitablePool" /> has been disposed.
 /// </exception>
 public IEnumerator <SocketAwaitable> GetEnumerator()
 {
     if (!IsDisposed)
     {
         return(_bag.GetEnumerator());
     }
     throw new ObjectDisposedException(TypeName);
 }
        static void ReadDataInternal()
        {
            var sb         = new StringBuilder();
            var enumerator = _storage.GetEnumerator();

            while (enumerator.MoveNext())
            {
                sb.Append($"{enumerator.Current}, ");
            }
            Console.WriteLine($"Peek result: {sb} count: {_counter}");
        }
Ejemplo n.º 5
0
        private void SetList <T>(ConcurrentBag <T> concurrent, Func <T, List <T>, bool> comparer, List <T> list)
        {
            var en = concurrent.GetEnumerator();

            while (en.MoveNext())
            {
                if (comparer(en.Current, list))
                {
                    list.Add(en.Current);
                }
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Shortcut to thread safe enumeration of Concurrent Bags
 /// </summary>
 /// <typeparam name="TVal"></typeparam>
 /// <param name="collection"></param>
 /// <param name="action"></param>
 public static void ForeachConcurrent <TVal>(
     this ConcurrentBag <TVal> collection,
     Action <TVal> action)
 {
     using (var enumerator = collection.GetEnumerator())
     {
         while (enumerator.MoveNext())
         {
             action(enumerator.Current);
         }
     }
 }
Ejemplo n.º 7
0
        public void UpdateUser(User user)
        {
            IEnumerator <KeyValuePair <int, User> > it = instance.GetEnumerator();

            foreach (var variable in instance)
            {
                if (variable.Key == user.Id)
                {
                    variable.Value.Name = user.Name;
                }
                else
                {
                    it.MoveNext();
                }
            }
        }
        public static void Clear_DuringEnumeration_DoesntAffectEnumeration()
        {
            const int ExpectedCount = 100;
            var       bag           = new ConcurrentBag <int>(Enumerable.Range(0, ExpectedCount));

            using (IEnumerator <int> e = bag.GetEnumerator())
            {
                bag.Clear();
                int count = 0;
                while (e.MoveNext())
                {
                    count++;
                }
                Assert.Equal(ExpectedCount, count);
            }
        }
Ejemplo n.º 9
0
        public static async Task GetEnumerator_Generic_ExpectedElementsYielded(int numItems, bool consumeFromSameThread)
        {
            var bag = new ConcurrentBag <int>();

            using (var e = bag.GetEnumerator())
            {
                Assert.False(e.MoveNext());
            }

            // Add, and validate enumeration after each item added
            for (int i = 1; i <= numItems; i++)
            {
                bag.Add(i);
                Assert.Equal(i, bag.Count);
                Assert.Equal(i, bag.Distinct().Count());
            }

            // Take, and validate enumerate after each item removed.
            Action consume = () =>
            {
                for (int i = 1; i <= numItems; i++)
                {
                    int item;
                    Assert.True(bag.TryTake(out item));
                    Assert.Equal(numItems - i, bag.Count);
                    Assert.Equal(numItems - i, bag.Distinct().Count());
                }
            };

            if (consumeFromSameThread)
            {
                consume();
            }
            else
            {
                await Task.Factory.StartNew(consume, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
        }
Ejemplo n.º 10
0
        public virtual async Task EnqueueMultipleItemsSucceeds()
        {
            // Arrange
            var(senderQueue, receiverQueue) = Create();
            var items = new ConcurrentBag <T>();
            var count = 100;

            for (int i = 0; i < count; i++)
            {
                var item = CreateItem();
                items.Add(item);
            }

            // Act
            var enumerator = items.GetEnumerator();
            var tasks      = Enumerable
                             .Range(0, count)
                             .Where(_ => enumerator.MoveNext())
                             .Select(_ => Task.Run(async() => await senderQueue.EnqueueAsync(enumerator.Current, CancellationToken)));

            await Task.WhenAll(tasks);

            // Assert

            foreach (var itemBag in items)
            {
                var item = await receiverQueue.DequeueAsync(CancellationToken);

                if (item == null)
                {
                    break;
                }

                AssertIsTrue(items.Contains(item));
            }
        }
Ejemplo n.º 11
0
 public IEnumerator <T> GetEnumerator()
 {
     return(_data.GetEnumerator());
 }
Ejemplo n.º 12
0
 public IEnumerator <Tuple <T, TimeSpan?> > GetEnumerator()
 {
     return(Enabled ? _bag.GetEnumerator() : new Bag <Tuple <T, TimeSpan?> >().GetEnumerator());
 }
Ejemplo n.º 13
0
 public IEnumerator <XOrder> GetEnumerator()
 {
     return(m_orders.GetEnumerator());
 }
 public IEnumerator <CacheKeyMapDescriptor> GetEnumerator()
 {
     return(mapList.GetEnumerator());
 }
Ejemplo n.º 15
0
 IEnumerator <Attribute> IEnumerable <Attribute> .GetEnumerator()
 {
     return(_attributes.GetEnumerator());
 }
Ejemplo n.º 16
0
 public IEnumerator <object> GetEnumerator()
 {
     return(m_buffer.GetEnumerator());
 }
Ejemplo n.º 17
0
 public IEnumerator <double> Enumerable()
 {
     return(bag.GetEnumerator());
 }
Ejemplo n.º 18
0
 public IEnumerator <T> GetEnumerator()
 {
     return(_available.GetEnumerator());
 }
Ejemplo n.º 19
0
 public IEnumerator <T> GetEnumerator()
 {
     return(_objects.GetEnumerator());
 }
Ejemplo n.º 20
0
 /// <inheritdoc/>
 IEnumerator GetEnumerator()
 => _rules.GetEnumerator();
 /// <summary>
 /// Returns an enumerator that iterates through a collection.
 /// </summary>
 /// <returns><see cref="System.Collections.Generic.IEnumerator&lt;IMediaTemplate&gt;" />.</returns>
 public IEnumerator <IMediaTemplate> GetEnumerator()
 {
     return(_items.GetEnumerator());
 }
Ejemplo n.º 22
0
 public IEnumerator <IValueTypeConverter> GetEnumerator()
 {
     return(_coverters.GetEnumerator());
 }
Ejemplo n.º 23
0
 IEnumerator IEnumerable.GetEnumerator()
 {
     return(_objects?.GetEnumerator());
 }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            // CONSTRUCTORS
            ConcurrentBag <int>    cbag = new ConcurrentBag <int>(new int[] { 1, 2, 4, 7, 12, 222 });
            ConcurrentBag <string> cb   = new ConcurrentBag <string>();

            // PROPERTIES
            Console.WriteLine("Count = {0}", cb.Count);        // 0
            Console.WriteLine("Is cb empty? {0}", cb.IsEmpty); // true

            // FUNCTIONS
            cb.Add(item: "cow");
            cb.Add(item: "chicken");
            cb.Add(item: "duck");
            cb.Add(item: "sheep");

            Console.WriteLine("cb = ");
            foreach (string s in cb)
            {
                Console.Write("{0}, ", s);
            }                                                       // {"cow", "chicken", "duck", "sheep"}
            Console.WriteLine();

            // cb.Clear();
            cb = new ConcurrentBag <string>();
            Console.WriteLine("cb after clear is empty? {0}", cb.IsEmpty); // true

            cb.Add(item: "Germany");
            cb.Add(item: "Spain");
            cb.Add(item: "Sweden");
            cb.Add(item: "Serbia");

            string[] arr = new string[cb.Count];
            cb.CopyTo(array: arr, index: 0);
            Console.WriteLine("arr = ");
            foreach (string s in arr)
            {
                Console.Write("{0}, ", s);
            }                                                        // {"Germany", "Spain", "Sweden", "Serbia"}
            Console.WriteLine();

            ConcurrentBag <string> cb_copy = new ConcurrentBag <string>(cb);

            Console.WriteLine("cb is equal to its copy? {0}", cb.Equals(cb_copy)); // true

            IEnumerator <string> en = cb.GetEnumerator();

            Console.Write("cb = ");
            while (en.MoveNext())
            {
                Console.Write("{0}, ", en.Current);
            }
            Console.WriteLine();

            Console.WriteLine("cb hashcode = {0}", cb.GetHashCode());

            Console.WriteLine("cb type = {0}", cb.GetType().FullName);

            arr = cb.ToArray();
            Console.WriteLine("arr afteer using ToArray on cb = ");
            foreach (string s in arr)
            {
                Console.Write("{0}, ", s);
            }                                                        // {"Germany", "Spain", "Sweden", "Serbia"}
            Console.WriteLine();

            Console.WriteLine("string version of cb = {0}", cb.ToString());

            string result_str;

            Console.WriteLine("peeking = {0}", cb.TryPeek(result: out result_str)); // true
            Console.WriteLine("peeking result = {0}", result_str);

            // Console.WriteLine("taking = {0}", cb.TryTaking(result: out result_str)); // true
            // Console.WriteLine("taking result = {0}", result_str);

            // Threading
            int    num       = 0;
            Thread threadAdd = new Thread(() => {
                for (int i = num; i < num + 10; i++)
                {
                    cb.Add(item: i.ToString());
                    Console.WriteLine("threadAdd: {0}", i);
                }
                num += 10;
                Console.WriteLine();
            });
            Thread threadAddWord = new Thread(() => {
                for (int i = 1; i < 10; i++)
                {
                    cb.Add(item: "Word");
                    Console.WriteLine("threadAddWord: {0}", i);
                }
                Console.WriteLine();
            });

            Thread threadFinal = new Thread(() => {
                Console.WriteLine("cb after threading = ");
                foreach (string s in cb)
                {
                    Console.Write("{0}, ", s);
                }
                Console.WriteLine();
            });

            threadAdd.Start();
            threadAddWord.Start();
            threadAdd.Join();
            threadAddWord.Join();
            threadFinal.Start();
        }
Ejemplo n.º 25
0
 public IEnumerator GetEnumerator()
 {
     return(_runtimeTypes.GetEnumerator());
 }
Ejemplo n.º 26
0
        public static void HandleClient(Object obj)
        {
            TcpClient client = (TcpClient)obj;

            StreamWriter writer  = new StreamWriter(client.GetStream(), Encoding.ASCII);
            TextWriter   sWriter = writer;

            Console.WriteLine("I got a connection");

            while (client.Connected)
            {
                StreamReader reader  = new StreamReader(client.GetStream(), Encoding.ASCII);
                TextReader   sReader = reader;

                try
                {
                    ChatCommand command = JsonSerializer.Deserialize <ChatCommand>(sReader.ReadLine());


                    switch (command.Command)
                    {
                    case Command.nick:
                        if (!connectedClients.ContainsKey(command.User))
                        {
                            Console.WriteLine("We have a new user: "******"they want to know what channels are available");

                        var index = channels.Keys.GetEnumerator();
                        var keys  = new StringBuilder();

                        while (index.MoveNext())
                        {
                            keys.Append(index.Current);
                            keys.Append(", ");
                        }

                        keys.Remove(keys.Length - 2, 1);
                        command.Message = keys.ToString();
                        command.Command = Command.receive_message;
                        sWriter.WriteLine(JsonSerializer.Serialize <ChatCommand>(command));
                        sWriter.Flush();
                        break;

                    case Command.join:
                        Console.WriteLine($"User {command.User} would like to join a channel {command.Arguments}");
                        if (channels.ContainsKey(command.Arguments))
                        {
                            ConcurrentBag <TcpClient> list = (ConcurrentBag <TcpClient>)channels[command.Arguments];
                            list.Add(client);
                        }
                        break;

                    case Command.leave:
                        break;

                    case Command.quit:
                        break;

                    case Command.help:
                        break;

                    case Command.stats:
                        break;

                    case Command.send_message:

                        ChatCommand newCommand = new ChatCommand
                        {
                            User      = "******",
                            Command   = Command.receive_message,
                            Arguments = String.Empty,
                            Message   = (String)command.Message.Clone()
                        };

                        Console.WriteLine($"user: {command.User}; Channel: {command.Arguments}; Message: {command.Message}");
                        ConcurrentBag <TcpClient> users = (ConcurrentBag <TcpClient>)channels[command.Arguments];
                        var currentTcpClient            = users.GetEnumerator();
                        foreach (TcpClient tcp in users)
                        {
                            if (tcp != client)
                            {
                                TextWriter w = new StreamWriter(tcp.GetStream(), Encoding.ASCII);
                                w.WriteLine(JsonSerializer.Serialize <ChatCommand>(newCommand));
                                w.Flush();
                            }
                        }
                        break;

                    default:
                        break;
                    }
                }
                catch (System.IO.IOException e)
                {
                    Console.Error.WriteLine(e.Message);
                }
            }
        }
Ejemplo n.º 27
0
 public IEnumerator <T> GetEnumerator()
 {
     return(_pool.GetEnumerator());
 }
Ejemplo n.º 28
0
 public static IEnumerator <T> GetEnumerator <T>(ConcurrentBag <T> concurrentBag)
 {
     ConcurrentCollectionHelper.Interleave();
     return(concurrentBag.GetEnumerator());
 }
Ejemplo n.º 29
0
 public IEnumerator <T> GetEnumerator() => collection.GetEnumerator();
Ejemplo n.º 30
0
 public IEnumerator <T> GetEnumerator()
 {
     return(_observations.GetEnumerator());
 }