本文整理汇总了C#中ConcurrentQueue.Enqueue方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentQueue.Enqueue方法的具体用法?C# ConcurrentQueue.Enqueue怎么用?C# ConcurrentQueue.Enqueue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentQueue
的用法示例。
在下文中一共展示了ConcurrentQueue.Enqueue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DemoConcurrentQueue
private static void DemoConcurrentQueue()
{
Console.WriteLine("Demo Concurrent Queue ----------------------");
// Initialize new concurrent queue, add three items to queue
var shirts = new ConcurrentQueue<string>();
shirts.Enqueue("Pluralsight");
shirts.Enqueue("WordPress");
shirts.Enqueue("Code School");
// 3
Console.WriteLine("After enqueuing, count = " + shirts.Count);
// based on whether queue is empty or not
string item1; //= shirts.Dequeue();
bool success = shirts.TryDequeue(out item1);
if (success)
Console.WriteLine("\r\nRemoving " + item1);
else
Console.WriteLine("queue was empty");
string item2; //= shirts.Peek();
success = shirts.TryPeek(out item2);
if (success)
Console.WriteLine("Peeking " + item2);
else
Console.WriteLine("queue was empty");
Console.WriteLine("\r\nEnumerating:");
foreach (string item in shirts)
Console.WriteLine(item);
Console.WriteLine("\r\nAfter enumerating, count = " + shirts.Count);
}
示例2: TestBasicScenarios
public static void TestBasicScenarios()
{
ConcurrentQueue<int> cq = new ConcurrentQueue<int>();
cq.Enqueue(1);
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
cq.Enqueue(2);
cq.Enqueue(3);
cq.Enqueue(4);
});
tks[1] = Task.Run(() =>
{
int item1, item2;
var ret1 = cq.TryDequeue(out item1);
// at least one item
Assert.True(ret1);
var ret2 = cq.TryDequeue(out item2);
// two item
if (ret2)
{
Assert.True(item1 < item2, String.Format("{0} should less than {1}", item1, item2));
}
else // one item
{
Assert.Equal(1, item1);
}
});
Task.WaitAll(tks);
}
示例3: TestGuardLock2
public void TestGuardLock2()
{
for (int i = 0; i != 10; ++i)
{
using (var guard = new AsyncLock())
{
var results = new ConcurrentQueue<int>();
var t2 = Task.Run(
async () =>
{
Thread.Sleep(TimeSpan.FromMilliseconds(200));
using (await guard.LockAsync(CancellationToken.None))
results.Enqueue(2);
});
var t1 = Task.Run(
async () =>
{
using (await guard.LockAsync(CancellationToken.None))
{
Thread.Sleep(TimeSpan.FromMilliseconds(400));
results.Enqueue(1);
}
});
Task.WaitAll(t1, t2);
var resultsData = results.ToArray();
Assert.Equal(1, resultsData[0]);
Assert.Equal(2, resultsData[1]);
}
}
}
示例4: StartBus
static IBus StartBus(InMemNetwork network, string queueName, ConcurrentQueue<string> recordedEvents)
{
var activator = new BuiltinHandlerActivator();
activator.Handle(async (string message) =>
{
recordedEvents.Enqueue($"GOT MESSAGE: {message}");
});
return Configure.With(activator)
.Transport(t => t.UseInMemoryTransport(network, queueName))
.Options(o =>
{
o.Decorate(c =>
{
var events = c.Get<BusLifetimeEvents>();
events.BusStarting += () => recordedEvents.Enqueue("Bus starting");
events.BusStarted += () => recordedEvents.Enqueue("Bus started");
events.BusDisposing += () => recordedEvents.Enqueue("Bus disposing");
events.BusDisposed += () => recordedEvents.Enqueue("Bus disposed");
return events;
});
})
.Start();
}
示例5: SubEvents
private void SubEvents()
{
Manager io = _io;
Subs = new ConcurrentQueue<On.IHandle>();
Subs.Enqueue(Client.On.Create(io, Manager.EVENT_OPEN, new ListenerImpl(OnOpen)));
Subs.Enqueue(Client.On.Create(io, Manager.EVENT_PACKET, new ListenerImpl((data) => OnPacket((Packet)data))));
Subs.Enqueue(Client.On.Create(io, Manager.EVENT_CLOSE, new ListenerImpl((data) => OnClose((string)data))));
}
示例6: SetUp
protected override void SetUp()
{
_receivedMessages = new ConcurrentQueue<string>();
_bus1 = CreateBus(TestConfig.QueueName("bus1"), async str => { });
_bus2 = CreateBus(TestConfig.QueueName("bus2"), async str =>
{
_receivedMessages.Enqueue("bus2 got " + str);
});
_bus3 = CreateBus(TestConfig.QueueName("bus3"), async str =>
{
_receivedMessages.Enqueue("bus3 got " + str);
});
}
示例7: Supervisor
public Supervisor()
{
_cq = new ConcurrentQueue<string>();
int i = 0;
while (i++ < 1000) {
int k = random.Next(0, 0x7ff);
if (k%2 == 0)
_cq.Enqueue("Read");
else {
_cq.Enqueue("Write");
}
}
readers = 0;
}
示例8: temp_test
public void temp_test()
{
int i;
// var func = Substitute.For<Func<void>(byte>();
ConcurrentQueue<int> qi = new ConcurrentQueue<int>();
ConcurrentQueue<int> qtemp;
qi.Enqueue(2);
qi.Enqueue(3);
qi.Enqueue(4);
qtemp = qi;
Assert.AreEqual(qtemp.Count, 3);
qtemp.TryDequeue(out i);
Assert.AreEqual(qi.Count, 2);
}
示例9: GetPayload
private static IEnumerable<StringEvent> GetPayload()
{
var messages = new ConcurrentQueue<StringEvent>();
messages.Enqueue(new StringEvent("Test1"));
messages.Enqueue(new StringEvent("Test2"));
messages.Enqueue(new StringEvent("Test3"));
messages.Enqueue(new StringEvent("Test4"));
messages.Enqueue(new StringEvent("Test5"));
messages.Enqueue(new StringEvent("Test6"));
messages.Enqueue(new StringEvent("Test7"));
messages.Enqueue(new StringEvent("Test8"));
messages.Enqueue(new StringEvent("Test9"));
messages.Enqueue(new StringEvent("Test10"));
return messages;
}
示例10: Do
public async Task Do()
{
var messages = new ConcurrentQueue<TransportMessage>();
messages.Enqueue(new TransportMessage());
messages.Enqueue(new TransportMessage());
messages.Enqueue(new TransportMessage());
var strategy = new PushMessages(messages, maxConcurrency: 1);
await strategy.StartAsync(HandleMessage);
await countdown.WaitAsync();
await strategy.StopAsync();
}
示例11: FillOne
public static byte[] FillOne(ConcurrentQueue<Operation> writeQueue, ConcurrentQueue<Operation> readQueue)
{
Operation op;
if (!writeQueue.TryDequeue(out op)) return new byte[0];
readQueue.Enqueue(op);
return op.Packet;
}
示例12: RegisterTypeAsParallel
/// <summary>
/// <para><see cref="IFrameworkContainer"/> 컨테이너에 등록할 개체를 Task Parallel Library 를 이용하여 병렬로 처리합니다.</para>
/// <para>단, 컨테이너에 개체를 등록할 때 CPU Process 의 개수를 이용하여 등록합니다.</para>
/// <para>단, 오버헤드가 높을 수 있는 작업이므로 <see cref="IFrameworkContainer"/> 의 내부적인 모든 작업을 병렬화 합니다.</para>
/// <para>단, 병렬 작업은 .NET Framework 4.0 빌드에서만 동작합니다.</para>
/// </summary>
/// <param name="container"></param>
/// <param name="action"></param>
public static void RegisterTypeAsParallel(this IFrameworkContainer container, IEnumerable<Action> action)
{
ConcurrentQueue<Exception> exceptions = null;
try
{
exceptions = new ConcurrentQueue<Exception>();
try
{
action.AsParallel()
.WithDegreeOfParallelism(Environment.ProcessorCount)
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.ForAll( o => o());
}
catch (Exception ex)
{
exceptions.Enqueue(ex);
}
}
catch (Exception)
{
if( exceptions != null )
exceptions.ToList().ForEach( o => Trace.WriteLine( o.Message ));
throw;
}
}
示例13: TestEtw
public void TestEtw()
{
using (var listener = new TestEventListener("System.Threading.Tasks.Parallel.EventSource", EventLevel.Verbose))
{
var events = new ConcurrentQueue<int>();
listener.RunWithCallback(ev => events.Enqueue(ev.EventId), () => {
Parallel.For(0, 10000, i => { });
var barrier = new Barrier(2);
Parallel.Invoke(
() => barrier.SignalAndWait(),
() => barrier.SignalAndWait());
});
const int BeginLoopEventId = 1;
const int BeginInvokeEventId = 3;
Assert.Equal(expected: 1, actual: events.Count(i => i == BeginLoopEventId));
Assert.Equal(expected: 1, actual: events.Count(i => i == BeginInvokeEventId));
const int EndLoopEventId = 2;
const int EndInvokeEventId = 4;
Assert.Equal(expected: 1, actual: events.Count(i => i == EndLoopEventId));
Assert.Equal(expected: 1, actual: events.Count(i => i == EndInvokeEventId));
const int ForkEventId = 5;
const int JoinEventId = 6;
Assert.True(events.Count(i => i == ForkEventId) >= 1);
Assert.Equal(events.Count(i => i == ForkEventId), events.Count(i => i == JoinEventId));
}
}
示例14: FakeDataQueue
/// <summary>
/// Initializes a new instance of the <see cref="FakeDataQueue"/> class to randomly emit data for each symbol
/// </summary>
public FakeDataQueue()
{
_ticks = new ConcurrentQueue<BaseData>();
_symbols = new Dictionary<SecurityType, List<string>>();
_timer = new Timer
{
AutoReset = true,
Enabled = true
};
_timer.Elapsed += (sender, args) =>
{
_timer.Interval = _random.Next(15, 2500); // around each second
foreach (var symbol in _symbols.SelectMany(x => x.Value))
{
// 50/50 repeating chance of emitting each symbol
while (_random.NextDouble() > 0.75)
{
_ticks.Enqueue(new Tick
{
Time = DateTime.Now,
Symbol = symbol,
Value = 10 + (decimal) Math.Abs(Math.Sin(DateTime.Now.TimeOfDay.TotalMinutes)),
TickType = TickType.Trade,
Quantity = _random.Next(10, (int) _timer.Interval)
});
}
}
};
}
示例15: CanEnumerateSafely
public void CanEnumerateSafely()
{
var strings = LangTestHelpers.RandomStrings(1000, 50);
var results = new ConcurrentQueue<string>();
using (var stringsEnumerator = strings.GetEnumerator())
{
var tse = new ThreadSafeEnumerator<string>(stringsEnumerator);
var threads = new List<Thread>();
for (var i = 0; i < 10; i++)
{
var thread = new Thread(() =>
{
string it = null;
while (tse.TryGetNext(ref it))
{
results.Enqueue(it);
}
});
thread.Start();
threads.Add(thread);
}
foreach (var thread in threads)
{
thread.Join();
}
}
CollectionAssert.AreEquivalent(strings, results);
}