本文整理汇总了C#中BlockingCollection.Take方法的典型用法代码示例。如果您正苦于以下问题:C# BlockingCollection.Take方法的具体用法?C# BlockingCollection.Take怎么用?C# BlockingCollection.Take使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BlockingCollection
的用法示例。
在下文中一共展示了BlockingCollection.Take方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestStreamingOneWayCommunication
public void TestStreamingOneWayCommunication()
{
IPAddress listeningAddress = IPAddress.Parse("127.0.0.1");
BlockingCollection<string> queue = new BlockingCollection<string>();
List<string> events = new List<string>();
IStreamingCodec<string> codec = TangFactory.GetTang().NewInjector().GetInstance<StringStreamingCodec>();
using (var remoteManager1 = _remoteManagerFactory1.GetInstance<string>(listeningAddress, codec))
using (var remoteManager2 = _remoteManagerFactory1.GetInstance<string>(listeningAddress, codec))
{
var observer = Observer.Create<string>(queue.Add);
IPEndPoint endpoint1 = new IPEndPoint(listeningAddress, 0);
remoteManager2.RegisterObserver(endpoint1, observer);
var remoteObserver = remoteManager1.GetRemoteObserver(remoteManager2.LocalEndpoint);
remoteObserver.OnNext("abc");
remoteObserver.OnNext("def");
remoteObserver.OnNext("ghi");
events.Add(queue.Take());
events.Add(queue.Take());
events.Add(queue.Take());
}
Assert.AreEqual(3, events.Count);
}
示例2: InternalCancellation_WakingUp
public static void InternalCancellation_WakingUp()
{
for (int test = 0; test < 2; test++)
{
BlockingCollection<int> coll1 = new BlockingCollection<int>(1);
coll1.Add(1); //fills the collection.
Assert.False(coll1.IsAddingCompleted,
"InternalCancellation_WakingUp: At this point CompleteAdding should not have occurred.");
// This is racy on what we want to test, in that it's possible this queued work could execute
// so quickly that CompleteAdding happens before the tested method gets invoked, but the test
// should still pass in such cases, we're just testing something other than we'd planned.
Task t = Task.Run(() => coll1.CompleteAdding());
// Try different methods that should wake up once CompleteAdding has been called
int item = coll1.Take(); // remove the existing item in the collection
switch (test)
{
case 0:
Assert.Throws<InvalidOperationException>(() => coll1.Take());
break;
case 1:
Assert.False(coll1.TryTake(out item));
break;
}
t.Wait();
Assert.True(coll1.IsAddingCompleted,
"InternalCancellation_WakingUp: At this point CompleteAdding should have occurred.");
}
}
示例3: TestWritableTransportServer
public void TestWritableTransportServer()
{
BlockingCollection<WritableString> queue = new BlockingCollection<WritableString>();
List<string> events = new List<string>();
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
var remoteHandler = Observer.Create<TransportEvent<WritableString>>(tEvent => queue.Add(tEvent.Data));
using (var server = new WritableTransportServer<WritableString>(endpoint, remoteHandler, _tcpPortProvider, _injector))
{
server.Run();
IPEndPoint remoteEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), server.LocalEndpoint.Port);
using (var client = new WritableTransportClient<WritableString>(remoteEndpoint, _injector))
{
client.Send(new WritableString("Hello"));
client.Send(new WritableString(", "));
client.Send(new WritableString("World!"));
events.Add(queue.Take().Data);
events.Add(queue.Take().Data);
events.Add(queue.Take().Data);
}
}
Assert.AreEqual(3, events.Count);
Assert.AreEqual(events[0], "Hello");
Assert.AreEqual(events[1], ", ");
Assert.AreEqual(events[2], "World!");
}
示例4: TestOneWayCommunicationClientOnly
public void TestOneWayCommunicationClientOnly()
{
IPAddress listeningAddress = IPAddress.Parse("127.0.0.1");
BlockingCollection<string> queue = new BlockingCollection<string>();
List<string> events = new List<string>();
using (var remoteManager1 = _remoteManagerFactory.GetInstance(new StringCodec()))
using (var remoteManager2 = _remoteManagerFactory.GetInstance(listeningAddress, new StringCodec()))
{
IPEndPoint remoteEndpoint = new IPEndPoint(listeningAddress, 0);
var observer = Observer.Create<string>(queue.Add);
remoteManager2.RegisterObserver(remoteEndpoint, observer);
var remoteObserver = remoteManager1.GetRemoteObserver(remoteManager2.LocalEndpoint);
remoteObserver.OnNext("abc");
remoteObserver.OnNext("def");
remoteObserver.OnNext("ghi");
events.Add(queue.Take());
events.Add(queue.Take());
events.Add(queue.Take());
}
Assert.Equal(3, events.Count);
}
示例5: TestStreamingTransportServer
public void TestStreamingTransportServer()
{
BlockingCollection<string> queue = new BlockingCollection<string>();
List<string> events = new List<string>();
IStreamingCodec<string> stringCodec = _injector.GetInstance<StringStreamingCodec>();
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
var remoteHandler = Observer.Create<TransportEvent<string>>(tEvent => queue.Add(tEvent.Data));
using (var server = new StreamingTransportServer<string>(endpoint.Address, remoteHandler, _tcpPortProvider, stringCodec))
{
server.Run();
IPEndPoint remoteEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), server.LocalEndpoint.Port);
using (var client = new StreamingTransportClient<string>(remoteEndpoint, stringCodec))
{
client.Send("Hello");
client.Send(", ");
client.Send("World!");
events.Add(queue.Take());
events.Add(queue.Take());
events.Add(queue.Take());
}
}
Assert.Equal(3, events.Count);
Assert.Equal(events[0], "Hello");
Assert.Equal(events[1], ", ");
Assert.Equal(events[2], "World!");
}
示例6: TestOfConstructor
public void TestOfConstructor()
{
BlockingCollection<string> dictionary = new BlockingCollection<string>();
new DictionaryReader(dictionary, "testing_dictionary.txt");
Assert.AreEqual("A",dictionary.Take());
Assert.AreEqual("Achomawi", dictionary.Take());
Assert.AreEqual("Achordata", dictionary.Take());
Assert.AreEqual("Achorion", dictionary.Take());
Assert.AreEqual("Achras", dictionary.Take());
}
示例7: TestCollectionContainsElement2
public void TestCollectionContainsElement2()
{
string item = "abc";
BlockingCollection<string> collection = new BlockingCollection<string>();
collection.Add("cat");
collection.Add(item);
collection.Add("dog");
Assert.Equal(item, collection.Take(item));
// Remove remaining items, check that item is not there
Assert.NotEqual(item, collection.Take());
Assert.NotEqual(item, collection.Take());
Assert.Equal(0, collection.Count);
}
示例8: Main
static void Main(string[] args)
{
BlockingCollection<String> col = new BlockingCollection<string>();
Task read = Task.Run(() =>
{
while (true)
{
Console.WriteLine(col.Take());
}
});
Task write = Task.Run(() =>
{
while (true)
{
string s = Console.ReadLine();
if (string.IsNullOrWhiteSpace(s))
{
break;
}
col.Add(s);
}
});
write.Wait();
}
示例9: ConsumerDispatcher
public ConsumerDispatcher(IEasyNetQLogger logger)
{
Preconditions.CheckNotNull(logger, "logger");
internalQueue = new ConcurrentQueue<Action>();
queue = new BlockingCollection<Action>(internalQueue);
dispatchThread = new Thread(_ =>
{
try
{
while (true)
{
if (disposed) break;
queue.Take()();
}
}
catch (InvalidOperationException)
{
// InvalidOperationException is thrown when Take is called after
// queue.CompleteAdding(), this is signals that this class is being
// disposed, so we allow the thread to complete.
}
catch (Exception exception)
{
logger.ErrorWrite(exception);
}
}) { Name = "EasyNetQ consumer dispatch thread" };
dispatchThread.Start();
}
示例10: Start
public void Start()
{
DateTime dt = System.DateTime.Now;
bool exists = Directory.Exists("./log");
if (!exists)
Directory.CreateDirectory("./log");
fileName = string.Format("./log/psd{0:D4}{1:D2}{2:D2}-{3:D2}{4:D2}{5:D2}.log",
dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
var ass = System.Reflection.Assembly.GetExecutingAssembly().GetName();
int version = ass.Version.Revision;
queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
Task.Factory.StartNew(() =>
{
using (StreamWriter sw = new StreamWriter(fileName, true))
{
sw.WriteLine("VERSION={0} ISSV=1", version);
sw.Flush();
Stop = false;
while (!Stop)
{
string line = queue.Take();
if (!string.IsNullOrEmpty(line))
{
string eline = Base.LogES.DESEncrypt(line, "AKB48Show!",
(version * version).ToString());
sw.WriteLine(eline);
sw.Flush();
}
}
}
});
}
示例11: ProcessReceive
public static void ProcessReceive( BlockingCollection<byte[]> inboundQueue, ConcurrentQueue<InProcPacket> pendingPackets, MessageContext context, CancellationToken cancellationToken )
{
InProcPacket packet;
if ( !pendingPackets.TryPeek( out packet ) )
{
byte[] data = inboundQueue.Take( cancellationToken );
packet = new InProcPacket( data );
pendingPackets.Enqueue( packet );
}
int copying = Math.Min( context.SocketContext.Count, packet.Data.Count );
Buffer.BlockCopy( packet.Data.Array, packet.Data.Offset, context.Buffer, context.Offset, copying );
context.SetBytesTransferred( copying );
if ( copying == packet.Data.Count )
{
InProcPacket dummy;
pendingPackets.TryDequeue( out dummy );
}
else
{
var oldData = packet.Data;
packet.Data = new ArraySegment<byte>( oldData.Array, oldData.Offset + copying, oldData.Count - copying );
}
}
示例12: Main
static void Main(string[] args)
{
// create a blocking collection
BlockingCollection<int> blockingCollection
= new BlockingCollection<int>();
// create and start a producer
Task.Factory.StartNew(() => {
// put items into the collectioon
for (int i = 0; i < 1000; i++) {
blockingCollection.Add(i);
}
// mark the collection as complete
blockingCollection.CompleteAdding();
});
// create and start a producer
Task.Factory.StartNew(() => {
while (!blockingCollection.IsCompleted) {
// take an item from the collection
int item = blockingCollection.Take();
// print out the item
Console.WriteLine("Item {0}", item);
}
});
// wait for input before exiting
Console.WriteLine("Press enter to finish");
Console.ReadLine();
}
示例13: BC_AddTakeCompleteAdding
// Demonstrates:
// BlockingCollection<T>.Add()
// BlockingCollection<T>.Take()
// BlockingCollection<T>.CompleteAdding()
public static void BC_AddTakeCompleteAdding()
{
using (BlockingCollection<int> bc = new BlockingCollection<int>()) {
// Spin up a Task to populate the BlockingCollection
using (Task t1 = Task.Factory.StartNew(() => {
bc.Add(1);
bc.Add(2);
bc.Add(3);
bc.CompleteAdding();
})) {
// Spin up a Task to consume the BlockingCollection
using (Task t2 = Task.Factory.StartNew(() => {
try {
// Consume the BlockingCollection
while (true) Console.WriteLine(bc.Take());
}
catch (InvalidOperationException) {
// An InvalidOperationException means that Take() was called on a completed collection
Console.WriteLine("That's All!");
}
}))
Task.WaitAll(t1, t2);
}
}
}
示例14: Main
public static void Main(string[] args)
{
// The program terminates when the user doesn’t enter any data.
// Until that, every string entered is added by the write Task and removed by the read Task.
BlockingCollection<string> collection = new BlockingCollection<string>();
Task read = Task.Run(() =>
{
while (true)
{
Console.WriteLine(collection.Take());
}
});
Task write = Task.Run(() =>
{
while (true)
{
string s = Console.ReadLine();
if (string.IsNullOrWhiteSpace(s))
break;
collection.Add(s);
}
});
write.Wait();
}
示例15: SpinCrcComputations
private static void SpinCrcComputations(BlockingCollection<CrcComputationWork> crcComputationWork)
{
// These computation actors will perform the actual CRC computation, we can
// probably optimize the CRC routine, but it is cheaper to just run it on multiple threads instead
// of going to near assembly in managed code.
// Our costs are going to be in the I/O mostly, anyway.
for (int i = 0; i < Math.Max(4, Environment.ProcessorCount); i++)
{
Task.Factory.StartNew(() =>
{
while (true)
{
var work = crcComputationWork.Take();
try
{
var crc = work.Crc();
Console.WriteLine("{0} = {1:x}", work.FileName, crc);
}
finally
{
// Now it goes back to the pool, and can be used again
foreach (var buffer in work.Buffers)
{
BufferPool.ReturnBuffer(buffer);
}
}
}
});
}
}