本文整理汇总了C#中BlockingQueue.Enqueue方法的典型用法代码示例。如果您正苦于以下问题:C# BlockingQueue.Enqueue方法的具体用法?C# BlockingQueue.Enqueue怎么用?C# BlockingQueue.Enqueue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BlockingQueue
的用法示例。
在下文中一共展示了BlockingQueue.Enqueue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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");
}
示例2: 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);
}
示例3: 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();
}
示例4: 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);
}
}
示例5: 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();
}
示例6: TestBlockingQueue
public static void TestBlockingQueue()
{
var bq = new BlockingQueue<int>();
var range = Arrays.Range(0, 1, 5);
var list = new List<int>();
for (int i = 0; i < 2 * range.Count; i++)
ThreadPool.QueueUserWorkItem((o) =>
{
int val;
if (!bq.TryDequeue(500, out val))
val = -1;
lock (list)
list.Add(val);
});
Thread.Sleep(10);
foreach (var i in range)
bq.Enqueue(i);
var now = DateTime.Now;
while ((DateTime.Now - now).TotalSeconds < 5)
{
lock (list)
if (list.Count >= 2 * range.Count)
{
if (list.Count > 2 * range.Count)
throw new Exception("Too many items");
if (list.Count(i => i == -1) != range.Count)
throw new Exception("Wrong number of -1's");
if (!list.Where(i => i != -1).InOrder().SequenceEqual(range))
throw new Exception("Wrong non-negative elements!");
return; // success
}
Thread.Sleep(10);
}
throw new Exception("Failed to complete after 5 seconds!");
}
示例7: Many_consumers_with_timeouts
public void Many_consumers_with_timeouts()
{
BlockingQueue<string> q = new BlockingQueue<string>();
Thread c1 = new Thread(MultiConsumer);
Thread c2 = new Thread(MultiConsumer);
Thread c3 = new Thread(MultiConsumer);
c1.IsBackground = true;
c2.IsBackground = true;
c3.IsBackground = true;
Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v1
= new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>(q, "x", TimeSpan.FromSeconds(1), new ManualResetEvent(false));
c1.Start(v1);
Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v2
= new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>(q, "x", TimeSpan.FromSeconds(1), new ManualResetEvent(false));
c2.Start(v2);
Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v3
= new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>(q, "x", TimeSpan.FromSeconds(1), new ManualResetEvent(false));
c3.Start(v3);
q.Enqueue("foo");
Assert.IsTrue(v1.Item4.WaitOne(2000, false), "thread 1 did not finish");
Assert.IsTrue(v2.Item4.WaitOne(2000, false), "thread 2 did not finish");
Assert.IsTrue(v3.Item4.WaitOne(2000, false), "thread 3 did not finish");
bool gotValue = false;
foreach(Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v in new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>[] { v1, v2, v3 }) {
if(v.Item2 == "foo") {
gotValue = true;
Assert.Less(v.Item3.TotalSeconds, 1);
} else {
Assert.IsNull(v.Item2);
Assert.GreaterOrEqual(v.Item3.TotalSeconds, 0.95);
}
}
Assert.IsTrue(gotValue);
}
示例8: PerformSearch
IEnumerator<object> PerformSearch(SearchQuery search)
{
pbProgress.Style = ProgressBarStyle.Marquee;
lblStatus.Text = String.Format("Starting search...");
lbResults.Items.Clear();
var filenames = new BlockingQueue<string>();
var completionFuture = new Future<object>();
using (var fileSearch = Program.Scheduler.Start(
SearchInFiles(search, filenames, completionFuture),
TaskExecutionPolicy.RunAsBackgroundTask
)) {
using (var iterator = BuildQuery(search)) {
var f = Program.Scheduler.Start(iterator.Fetch());
yield return f;
if (!f.Failed) {
txtSearch.BackColor = SystemColors.Window;
while (!iterator.Disposed) {
if (PendingSearchQuery != null)
break;
foreach (var current in iterator)
filenames.Enqueue(current.Path);
yield return iterator.Fetch();
}
} else {
txtSearch.BackColor = ErrorColor;
}
}
completionFuture.Complete();
while (filenames.Count < 0)
filenames.Enqueue(null);
yield return fileSearch;
}
if (PendingSearchQuery != null) {
yield return BeginSearch();
} else {
pbProgress.Value = 0;
pbProgress.Style = ProgressBarStyle.Continuous;
}
}
示例9: Single_threaded_queue_dequeue
public void Single_threaded_queue_dequeue()
{
int n = 10000;
List<string> guids = new List<string>();
BlockingQueue<string> q = new BlockingQueue<string>();
for(int i = 0; i < n; i++) {
string guid = Guid.NewGuid().ToString();
q.Enqueue(guid);
guids.Add(guid);
}
Assert.AreEqual(n, q.Count);
for(int i = 0; i < n; i++) {
string guid = q.Dequeue();
Assert.AreEqual(guids[i], guid);
}
}
示例10: Queue_on_closed_queue_throws
public void Queue_on_closed_queue_throws()
{
BlockingQueue<string> q = new BlockingQueue<string>();
q.Enqueue("foo");
Assert.IsFalse(q.IsClosed);
q.Close();
Assert.IsTrue(q.IsClosed);
q.Enqueue("bar");
}
示例11: One_producer_one_consumer_loop_with_foreach_and_stop
public void One_producer_one_consumer_loop_with_foreach_and_stop()
{
int n = 10000;
List<string> enqueued = new List<string>();
List<string> dequeued = new List<string>();
BlockingQueue<string> q = new BlockingQueue<string>();
Thread consumer = new Thread(SingleConsumerForeachLoopAndStop);
consumer.Start(new Tuplet<IBlockingQueue<string>, List<string>>(q, dequeued));
for(int i = 0; i < n; i++) {
string guid = Guid.NewGuid().ToString();
q.Enqueue(guid);
enqueued.Add(guid);
}
q.Close();
Assert.IsTrue(consumer.Join(1000));
Assert.AreEqual(n, enqueued.Count);
Assert.AreEqual(n, dequeued.Count);
for(int i = 0; i < n; i++) {
Assert.AreEqual(enqueued[i], dequeued[i]);
}
}
示例12: One_producer_one_consumer_loop_with_foreach
public void One_producer_one_consumer_loop_with_foreach()
{
var n = 10000;
var enqueued = new List<string>();
var dequeued = new List<string>();
var q = new BlockingQueue<string>();
var consumer = new Thread(SingleConsumerForeachLoop);
consumer.IsBackground = true;
var reset = new ManualResetEvent(false);
consumer.Start(new Tuplet<int, IBlockingQueue<string>, List<string>, ManualResetEvent>(n, q, dequeued, reset));
for(int i = 0; i < n; i++) {
string guid = Guid.NewGuid().ToString();
q.Enqueue(guid);
enqueued.Add(guid);
}
Assert.IsTrue(reset.WaitOne(1000, true));
Assert.AreEqual(n, enqueued.Count);
Assert.AreEqual(n, dequeued.Count);
for(int i = 0; i < n; i++) {
Assert.AreEqual(enqueued[i], dequeued[i]);
}
}
示例13: ScanFiles
public static IEnumerator<object> ScanFiles()
{
var time_start = DateTime.UtcNow.Ticks;
var completion = new Future<object>();
var batchQueue = new BlockingQueue<IEnumerable<string>>();
var changedFiles = new List<string>();
var deletedFiles = new List<string>();
for (int i = 0; i < System.Environment.ProcessorCount; i++)
Scheduler.Start(
CommitBatches(batchQueue, completion),
TaskExecutionPolicy.RunAsBackgroundTask
);
using (new ActiveWorker("Scanning folders for changes")) {
var changeSet = new BlockingQueue<TagDatabase.Change>();
var changeGenerator = Scheduler.Start(
Database.UpdateFileListAndGetChangeSet(changeSet),
TaskExecutionPolicy.RunAsBackgroundTask
);
changeGenerator.RegisterOnComplete((f) => changeSet.Enqueue(new TagDatabase.Change()));
int numChanges = 0;
int numDeletes = 0;
while (!changeGenerator.Completed || (changeSet.Count > 0)) {
var f = changeSet.Dequeue();
yield return f;
var change = f.Result;
if (change.Filename == null)
continue;
if (change.Deleted) {
deletedFiles.Add(change.Filename);
numDeletes += 1;
} else {
yield return Database.GetSourceFileID(change.Filename);
changedFiles.Add(change.Filename);
numChanges += 1;
}
if (deletedFiles.Count >= BatchSize) {
var transaction = Database.Connection.CreateTransaction();
yield return transaction;
foreach (string filename in deletedFiles)
yield return Database.DeleteSourceFile(filename);
deletedFiles.Clear();
yield return transaction.Commit();
}
if (changedFiles.Count >= BatchSize) {
string[] batch = changedFiles.ToArray();
changedFiles.Clear();
batchQueue.Enqueue(batch);
}
}
if (deletedFiles.Count > 0) {
var transaction = Database.Connection.CreateTransaction();
yield return transaction;
foreach (string filename in deletedFiles)
yield return Database.DeleteSourceFile(filename);
deletedFiles.Clear();
yield return transaction.Commit();
}
if (changedFiles.Count > 0) {
string[] batch = changedFiles.ToArray();
batchQueue.Enqueue(batch);
}
completion.Complete();
while (batchQueue.Count < 0)
batchQueue.Enqueue(null);
var time_end = DateTime.UtcNow.Ticks;
var elapsed = TimeSpan.FromTicks(time_end - time_start).TotalSeconds;
System.Diagnostics.Debug.WriteLine(String.Format("Disk scan complete after {2:00000.00} seconds. {0} change(s), {1} delete(s).", numChanges, numDeletes, elapsed));
}
}
示例14: TestBlockingQueue
public void TestBlockingQueue()
{
Initialize();
BlockingQueue<int> queue = new BlockingQueue<int>();
ItemDelegate<int> addToQueue = delegate(int numberToAdd)
{
for (int i = 0; i < numberToAdd; ++i)
{
queue.Enqueue(1);
}
this.IncrementEnqueued(numberToAdd);
this.IncrementExpectedDequeued(numberToAdd);
};
addToQueue(100000);
ThreadStart start = delegate()
{
while (true)
{
int next;
bool queueEmpty = !queue.Dequeue(out next);
if (queueEmpty)
{
if (_stopThreads)
break;
}
else
{
this.IncrementDequeued(1);
}
Thread.Sleep(0);
}
};
List<Thread> threads = new List<Thread>();
for (int i = 0; i < _threadCount; ++i)
{
Thread thread = new Thread(start);
thread.Start();
threads.Add(thread);
}
//continually add to the queue a bit.
int numberTimesAdded = 0;
for (int i = 0; i < _threadCount; ++i)
{
addToQueue(100000);
Thread.Sleep(5);
}
//'pulse' the queue by letting it go empty, then adding more.
numberTimesAdded = 0;
while (true)
{
if (queue.Count == 0)
{
if (++numberTimesAdded <= _threadCount)
{
addToQueue(100000);
}
else
{
//the real test of exiting the queue is when it's empty, not when it's non-empty.
queue.ContinueBlocking = false;
break;
}
}
Thread.Sleep(5);
}
_stopThreads = true;
foreach (Thread thread in threads)
thread.Join();
threads.Clear();
Assert.AreEqual(_expectedDequeued, _dequeued, "expectedValue != numberDequeued");
}
示例15: StartServices
public static void StartServices() {
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
IBlockingQueue<ServiceBE> services = new BlockingQueue<ServiceBE>();
List<ServiceBE> servicesToStart = new List<ServiceBE>(DbUtils.CurrentSession.Services_GetAll());
// extract all auth services and start them synchronously first
List<ServiceBE> authServices = servicesToStart.FindAll(service => service.Type == ServiceType.AUTH);
servicesToStart.RemoveAll(service => service.Type == ServiceType.AUTH);
foreach(ServiceBE authService in authServices) {
try {
StartService(authService, false, false);
} catch {
//Services started on deki startup do not get disabled if they fail to start
}
}
// start remaining services in parallel
foreach(ServiceBE service in servicesToStart) {
if(service.ServiceEnabled) {
services.Enqueue(service);
}
}
services.Close();
List<Result> workers = new List<Result>();
for(int i = 0; i < 10; i++) {
workers.Add(Async.ForkThread(() => StartServices_Helper(services), new Result()));
}
workers.Join(new Result()).Wait();
_log.InfoFormat("Services started for instance '{0}' in {1}ms", DekiContext.Current.Instance.Id, stopwatch.ElapsedMilliseconds);
}