当前位置: 首页>>代码示例>>C#>>正文


C# BlockingQueue.Dequeue方法代码示例

本文整理汇总了C#中BlockingQueue.Dequeue方法的典型用法代码示例。如果您正苦于以下问题:C# BlockingQueue.Dequeue方法的具体用法?C# BlockingQueue.Dequeue怎么用?C# BlockingQueue.Dequeue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BlockingQueue的用法示例。


在下文中一共展示了BlockingQueue.Dequeue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Dequeue_on_closed_queue_throws

 public void Dequeue_on_closed_queue_throws()
 {
     BlockingQueue<string> q = new BlockingQueue<string>();
     q.Enqueue("foo");
     Assert.IsFalse(q.IsClosed);
     q.Close();
     Assert.IsTrue(q.IsClosed);
     string x = q.Dequeue();
     Assert.AreEqual("foo", x);
     x = q.Dequeue();
 }
开发者ID:nataren,项目名称:DReAM,代码行数:11,代码来源:BlockingQueueTests.cs

示例2: EnqueueBeforeDequeueTest

        public void EnqueueBeforeDequeueTest()
        {
            var queue = new BlockingQueue<object>();
            var isEnqueued = new ManualResetEvent(false);
            var isDequeued = new ManualResetEvent(false);

            object value = null;

            ThreadPool.QueueUserWorkItem(_ =>
            {
                queue.Enqueue(new object());
                isEnqueued.Set();
            });
            ThreadPool.QueueUserWorkItem(_ =>
            {
                isEnqueued.WaitOne();
                value = queue.Dequeue();
                isDequeued.Set();
            });

            if (!isDequeued.WaitOne(10))
                Assert.Fail("Dequeue after Enqueue failed: Event hasn't been raised");

            if(value == null)
                Assert.Fail("Dequeue after Enqueue failed: Wrong value returned");
        }
开发者ID:kapitanov,项目名称:diploma,代码行数:26,代码来源:BlockingQueueTest.cs

示例3: MultipleInstanceMongoServerProxy

        /// <summary>
        /// Initializes a new instance of the <see cref="ShardedMongoServerProxy"/> class.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="instances">The instances.</param>
        /// <param name="connectionQueue">The state change queue.</param>
        /// <param name="connectionAttempt">The connection attempt.</param>
        /// <remarks>This constructor is used when the instances have already been instructed to connect.</remarks>
        protected MultipleInstanceMongoServerProxy(MongoServer server, IEnumerable<MongoServerInstance> instances, BlockingQueue<MongoServerInstance> connectionQueue, int connectionAttempt)
        {
            _state = MongoServerState.Connecting;
            _server = server;
            _connectedInstances = new ConnectedInstanceCollection();
            _connectionAttempt = connectionAttempt;

            _outstandingInstanceConnections = connectionQueue.Count;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                while (connectionQueue.Count > 0)
                {
                    var instance = connectionQueue.Dequeue();
                    Interlocked.Decrement(ref _outstandingInstanceConnections);
                }
            });

            // It's important to have our own copy of this list because it might get modified during iteration. 
            _instances = instances.ToList();
            foreach (var instance in instances)
            {
                instance.StateChanged += InstanceStateChanged;
                ProcessInstanceStateChange(instance);
            }
        }
开发者ID:nickgervasi,项目名称:mongo-csharp-driver,代码行数:33,代码来源:MultipleInstanceMongoServerProxy.cs

示例4: CreateAndUseBlockingQueue

        public void CreateAndUseBlockingQueue()
        {
            BlockingQueue<int> queue = new BlockingQueue<int>(1);

            Thread thread = new Thread(new ThreadStart(delegate() { queue.Enqueue(1); }));
            thread.Start();

            int element = queue.Dequeue();
            Assert.AreEqual(1, element);
        }
开发者ID:ajlopez,项目名称:AjActors,代码行数:10,代码来源:BlockingQueueTests.cs

示例5: CreateAndUseBlockingQueueTenTimes

        public void CreateAndUseBlockingQueueTenTimes()
        {
            BlockingQueue<int> queue = new BlockingQueue<int>(5);

            Thread thread = new Thread(new ThreadStart(delegate() { for (int k=1; k<=10; k++) queue.Enqueue(k); }));
            thread.Start();

            for (int j = 1; j <= 10; j++)
            {
                int element = queue.Dequeue();
                Assert.AreEqual(element, j);
            }
        }
开发者ID:ajlopez,项目名称:AjActors,代码行数:13,代码来源:BlockingQueueTests.cs

示例6: AddBuddy

 /// <summary>
 /// This mehod allows the client to add a buddy to the network which 
 /// is used for DNS, ip translation
 /// </summary>
 /// <param name="name">A string DNS name used to register the address</param>
 /// <param name="address">A string brunet address</param>
 /// <returns>A string IP address for the added name</returns>
 public string AddBuddy(string name, string address)
 {
     BlockingQueue q = new BlockingQueue();
     _brpc.Rpc.Invoke(_brpc.IPHandler.CreateUnicastSender(_remEP), q, "RpcIpopNode.RegisterMapping", name, address);
     try {
       RpcResult res = (RpcResult)q.Dequeue();
       Console.WriteLine(_remEP + ":" + ((UnicastSender)res.ResultSender).EndPoint);
       Console.WriteLine(res.Result);
       return (string)res.Result;
     }
     catch (InvalidOperationException e) {
       Console.WriteLine(e.Message);
     }
     catch (Exception e) {
       Console.WriteLine(e.Message);
     }
     return null;
 }
开发者ID:kyungyonglee,项目名称:ipop,代码行数:25,代码来源:RpcDNSClient.cs

示例7: Queue

        public void Queue()
        {
            BlockingQueue<string> queue = new BlockingQueue<string>();

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(DoWork);
            worker.ProgressChanged += new ProgressChangedEventHandler(DoProgressChanged);
            worker.WorkerReportsProgress = true;
            worker.RunWorkerAsync(queue);

            int count = 0;
            while (count < 5)
            {
                string s = queue.Dequeue();
                Console.WriteLine("dequeued " + count + "(" + s + ")");
                count++;
            }

            queue.Clear();
            queue.Dispose();
            queue = null;
        }
开发者ID:pengyancai,项目名称:cs-util,代码行数:22,代码来源:BlockQueueTests.cs

示例8: Test

        public void Test()
        {
            var q = new BlockingQueue<int>(4);

            // Producer
            new Thread(() =>
            {
                for (var x = 0;; x++)
                {
                    if (!q.Enqueue(x))
                        break;
                    Trace.WriteLine(x.ToString("0000") + " >");
                }
                Trace.WriteLine("Producer quitting");
            }).Start();

            // Consumers
            for (var i = 0; i < 2; i++)
            {
                new Thread(() =>
                {
                    for (;;)
                    {
                        Thread.Sleep(100);
                        int x;
                        if (!q.Dequeue(out x))
                            break;
                        Trace.WriteLine("     < " + x.ToString("0000"));
                    }
                    Trace.WriteLine("Consumer quitting");
                }).Start();
            }

            Thread.Sleep(2000);

            Trace.WriteLine("Quitting");

            q.Quit();
        }
开发者ID:Dmdv,项目名称:ThreadingPatterns,代码行数:39,代码来源:BlockingQueueTests.cs

示例9: Crawl

    private static void Crawl() {
      int count = 0, consistency = 0;
      NodeMapping nm = (NodeMapping) nodes.GetByIndex(0);
      Node lnode = nm.Node;
      Address rem_addr = lnode.Address, prev = null, first_left = null;
      bool failed = false;
      try {
        do {
          Console.WriteLine("Current address: " + rem_addr);
          ISender sender = new AHGreedySender(lnode, rem_addr);
          BlockingQueue q = new BlockingQueue();
          lnode.Rpc.Invoke(sender, q, "sys:link.GetNeighbors");
          RpcResult res = (RpcResult) q.Dequeue();
          Hashtable ht = (Hashtable) res.Result;

          Address tmp = AddressParser.Parse((String) ht["left"]);
          Address next = AddressParser.Parse((String) ht["right"]);
          if(prev != null && tmp.Equals(prev)) {
            consistency++;
          }
          else {
            first_left = tmp;
          }
          if(next == lnode.Address && first_left == rem_addr) {
            consistency++;
          }
          prev = rem_addr;
          rem_addr = next;
          q.Close();
          count++;
        } while((rem_addr != lnode.Address) && (count < nodes.Count));
      }
      catch(Exception e) {
        failed = true;
        Console.WriteLine("Crawl failed due to exception...");
        Console.WriteLine(e);
      }
      if(!failed) {
        if(count != nodes.Count) {
          Console.WriteLine("Crawl failed due to missing nodes!");
          Console.WriteLine("Expected nodes: {0}, found: {1}.", nodes.Count, count);
        }
        else if(consistency != count) {
          Console.WriteLine("Crawl failed due to bad consistency!");
          Console.WriteLine("Expected consistency: {0}, actual: {1}.", count, consistency);
        }
        else {
          Console.WriteLine("Crawl succeeded!");
        }
      }
    }
开发者ID:xujyan,项目名称:brunet,代码行数:51,代码来源:SystemTest.cs

示例10: Main

//    static Hashtable taken_ports = new Hashtable();
//    static ArrayList RemoteTA = new ArrayList();

    public static void Main(string []args) {
      if (args.Length < 6) {
        Console.WriteLine("Input format %1 %2 %3 %4 %5 %6");
        Console.WriteLine("\t%1 = [network size]");
        Console.WriteLine("\t%2 = [base time]");
        Console.WriteLine("\t%3 = [add/remove interval]");
        Console.WriteLine("\t%4 = [add/remove delta]");
        Console.WriteLine("\t%5 = [dht put interval]");
        Console.WriteLine("\t%6 = [dht get interval]");
        Console.WriteLine("Specifying 3, 4, 5, 6 disables the event.");
        Environment.Exit(0);
      }

      int starting_network_size = Int32.Parse(args[0]);
      max_range = starting_network_size;

      base_time = Int32.Parse(args[1]);
      add_remove_interval = Int32.Parse(args[2]);
      add_remove_delta = Int32.Parse(args[3]);
      dht_put_interval = Int32.Parse(args[4]);
      dht_get_interval = Int32.Parse(args[5]);
      Console.WriteLine("Initializing...");

      for(int i = 0; i < starting_network_size; i++) {
        Console.WriteLine("Setting up node: " + i);
        add_node();
      }
      Console.WriteLine("Done setting up...\n");

      Thread system_thread = new Thread(system);
      system_thread.IsBackground = true;
      system_thread.Start();

      string command = String.Empty;
      while (command != "Q") {
        Console.WriteLine("Enter command (M/C/P/G/Q)");
        command = Console.ReadLine();
        if(command.Equals("C")) {
          check_ring();
        }
        else if(command.Equals("P")) {
          PrintConnections();
        }
        else if(command.Equals("M")) {
          Console.WriteLine("Memory Usage: " + GC.GetTotalMemory(true));
        }
        else if(command.Equals("G")) {
          Node node = (Node) nodes.GetByIndex(rand.Next(0, network_size));
          Dht dht = (Dht) dhts[node];
          if(!dht.Activated)
            continue;
          BlockingQueue returns = new BlockingQueue();
          dht.AsGet("tester", returns);
          int count = 0;
          try {
            while(true) {
              returns.Dequeue();
              count++;
            }
          }
          catch {}
          Console.WriteLine("Count: " + count);
        }
        Console.WriteLine();
      }

      system_thread.Abort();

      int lcount = 0;
      foreach(DictionaryEntry de in nodes) {
        Console.WriteLine(lcount++);
        Node node = (Node)de.Value;
        node.Disconnect();
      }
    }
开发者ID:xujyan,项目名称:brunet,代码行数:78,代码来源:SystemTesterWithZeroConf.cs

示例11: SerialAsyncGet

 public void SerialAsyncGet(object data) {
   Hashtable ht = (Hashtable) data;
   byte[] key = (byte[]) ht["key"];
   byte[][] expected_results = (byte[][]) ht["results"];
   int op = (int) ht["op"];
   try {
     BlockingQueue queue = new BlockingQueue();
     default_dht.AsyncGet(key, queue);
     bool found = false;
     int found_count = 0;
     while(true) {
       Hashtable dgr = null;
       try {
         dgr = (Hashtable) queue.Dequeue();
       }
       catch(Exception){
           break;
       }
       for(int j = 0; j < expected_results.Length; j++) {
         if(ArrayComparer((byte[]) dgr["value"], expected_results[j])) {
           found = true;
           break;
         }
       }
       if(found) {
         found_count++;
         found =  false;
       }
     }
     if(found_count != expected_results.Length) {
       lock(_lock) {
         Console.WriteLine("Failed get... attempted to get " + 
             expected_results.Length + " found " + found_count +
             " operation: " + op);
       }
     }
   }
   catch(Exception e) {
     Console.WriteLine("Failure at operation: " + op);
     Console.WriteLine(e);
     throw e;
   }
 }
开发者ID:johnynek,项目名称:brunet,代码行数:43,代码来源:DhtTest.cs

示例12: Discover

        private void Discover(TimeSpan timeout)
        {
            var connectionQueue = new BlockingQueue<MongoServerInstance>();

            for (int i = 0; i < _instances.Count; i++)
            {
                var local = _instances[i];
                connectionQueue.EnqueuWorkItem(() =>
                {
                    try
                    {
                        local.Connect();
                    }
                    catch
                    {
                        // instance is keeping it's last ConnectionException
                    }
                    return local;
                });
            }

            MongoServerInstance instance = null;
            var timeoutAt = DateTime.UtcNow;
            while ((instance = connectionQueue.Dequeue(timeout)) != null)
            {
                if (instance.ConnectException == null)
                {
                    CreateActualProxy(instance, connectionQueue);
                    return;
                }

                timeout = DateTime.UtcNow - timeoutAt;
            }

            throw new MongoConnectionException(string.Format("Unable to connect in the specified timeframe of '{0}'.", timeout));
        }
开发者ID:robinNode,项目名称:mongo-csharp-driver,代码行数:36,代码来源:DiscoveringMongoServerProxy.cs

示例13: CommitBatches

        public static IEnumerator<object> CommitBatches(BlockingQueue<IEnumerable<string>> batches, IFuture completion)
        {
            while (batches.Count > 0 || !completion.Completed) {
                var f = batches.Dequeue();
                yield return f;

                var batch = f.Result as IEnumerable<string>;
                if (batch != null)
                    yield return UpdateIndex(batch);
            }
        }
开发者ID:pazjacket,项目名称:malys-_-NDexer,代码行数:11,代码来源:Program.cs

示例14: Init

 /// <summary>
 /// This method looks for the RpcIpopNode running on the localhost and
 /// sets an Endpoint for future unicast communication
 /// </summary>
 public void Init()
 {
     BlockingQueue q = new BlockingQueue();
     _brpc.Rpc.Invoke(_brpc.IPHandler.CreateMulticastSender(loopback), q, "RpcIpopNode.CheckInstance");
     while (true) {
       try {
     RpcResult res = (RpcResult)q.Dequeue();
     _remEP = ((UnicastSender)res.ResultSender).EndPoint;
     if ((bool)res.Result) {
       break;
     }
       }
       catch (InvalidOperationException e) {
     Console.WriteLine(e.Message);
     break;
       }
       catch (Exception e) {
     Console.WriteLine(e.Message);
     continue;
       }
     }
 }
开发者ID:kyungyonglee,项目名称:ipop,代码行数:26,代码来源:RpcDNSClient.cs

示例15: Main

        /**
         * Simple program to find out if any Grid Appliances are running on the
         * local system!
         */
        public static void Main(String[] args)
        {
            ISender sender = null;
              BrunetRpc brpc = new BrunetRpc();
              if(args.Length == 0) {
            // Step one:  Gather all non-VMware IP Addresses for the block list
            ArrayList local_ips = new ArrayList();
            IPAddresses ipaddrs = IPAddresses.GetIPAddresses();
            foreach(Hashtable ht in ipaddrs.AllInterfaces) {
              if(ht["inet addr"] == null) {
            continue;
              }
              string ifname = (string) ht["interface"];
              if(ifname.StartsWith("vmnet") || ifname.StartsWith("VMware")) {
            local_ips.Add(IPAddress.Parse((String) ht["inet addr"]));
              }
            }
            IPAddress[] lips = (IPAddress[]) local_ips.ToArray(typeof(IPAddress));
            sender = brpc.IPHandler.CreateMulticastSender(lips);
              }
              else {
            sender = brpc.IPHandler.CreateMulticastSender();
              }

              // Step two: Setup BrunetRpc using Multicast to find nodes
              BlockingQueue q = new BlockingQueue();
              brpc.Rpc.Invoke(sender, q, "Information.Info");
              Hashtable retrieved = new Hashtable();
              while(true) {
            RpcResult res = null;
            try {
              // Step three: Get result and print it, need something better for autmoated service
              bool timedout = false;
              res = (RpcResult) q.Dequeue(2000, out timedout);
              if(timedout) {
            break;
              }
              Hashtable ht = (Hashtable) res.Result;
              Hashtable neighbors = (Hashtable) ht["neighbors"];
              string self = (string) neighbors["self"];
              if(retrieved.Contains(self)) {
            continue;
              }
              retrieved[self] = true;

              ArrayList vips = ht["VirtualIPs"] as ArrayList;

              string vips_list = "";
              if(vips != null) {
            foreach(string ip in vips) {
              vips_list += ip + ", ";
            }
            vips_list = vips_list.Substring(0, vips_list.Length - 2);
              }

              ArrayList ips = (ArrayList) ht["localips"];
              string iplist = "";
              foreach(string ip in ips) {
            iplist += ip + ", ";
              }
              iplist = iplist.Substring(0, iplist.Length - 2);

              Console.WriteLine(vips_list + ": " + iplist);
            }
            //This occurs when all attempts are done, unless you close the queue first
            catch(InvalidOperationException) {
              break;
            }
            catch(Exception e) {}
              }
              //BrunetRpc has a timer thread, it needs to explicitly be closed
              brpc.Close();
        }
开发者ID:davidiw,项目名称:Grid-Appliance-Tools,代码行数:77,代码来源:Locator.cs


注:本文中的BlockingQueue.Dequeue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。