本文整理汇总了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();
}
示例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");
}
示例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);
}
}
示例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);
}
示例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);
}
}
示例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;
}
示例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;
}
示例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();
}
示例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!");
}
}
}
示例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();
}
}
示例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;
}
}
示例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));
}
示例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);
}
}
示例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;
}
}
}
示例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();
}