本文整理汇总了C#中ConcurrentBag.TryTake方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentBag.TryTake方法的具体用法?C# ConcurrentBag.TryTake怎么用?C# ConcurrentBag.TryTake使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentBag
的用法示例。
在下文中一共展示了ConcurrentBag.TryTake方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
bag.Add(42);
bag.Add(21);
int result;
if (bag.TryTake(out result))
{
Console.WriteLine(result);
}
if (bag.TryPeek(out result))
{
Console.WriteLine("There is a next item: {0}", result);
}
if (bag.TryTake(out result))
{
Console.WriteLine(result);
}
Console.Write("Press a key to exit");
Console.ReadKey();
}
示例2: Main
static void Main(string[] args)
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
bag.Add(123);
bag.Add(321);
bag.Add(123123);
int result;
if (bag.TryTake(out result))
{
Console.WriteLine(result);
}
if (bag.TryTake(out result))
{
Console.WriteLine(result);
}
if (bag.TryPeek(out result))
{
Console.WriteLine("There is a next itam: {0}", result);
}
Console.ReadLine();
}
示例3: DemoConcurrentBag
private static void DemoConcurrentBag()
{
Console.WriteLine("Demo Concurrent Bag ----------------------");
var shirts = new ConcurrentBag<string>();
shirts.Add("Pluralsight");
shirts.Add("WordPress");
shirts.Add("Code School");
Console.WriteLine("After enqueuing, count = " + shirts.Count);
string item1; //= shirts.Dequeue();
bool success = shirts.TryTake(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);
}
示例4: TestBasicScenarios
public static void TestBasicScenarios()
{
ConcurrentBag<int> cb = new ConcurrentBag<int>();
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
cb.Add(4);
cb.Add(5);
cb.Add(6);
});
// Consume the items in the bag
tks[1] = Task.Run(() =>
{
int item;
while (!cb.IsEmpty)
{
bool ret = cb.TryTake(out item);
Assert.True(ret);
// loose check
Assert.Contains(item, new[] { 4, 5, 6 });
}
});
Task.WaitAll(tks);
}
示例5: TestBasicScenarios
public static void TestBasicScenarios()
{
ConcurrentBag<int> cb = new ConcurrentBag<int>();
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
cb.Add(4);
cb.Add(5);
cb.Add(6);
});
// Consume the items in the bag
tks[1] = Task.Run(() =>
{
int item;
while (!cb.IsEmpty)
{
bool ret = cb.TryTake(out item);
Assert.True(ret);
// loose check
if (item != 4 && item != 5 && item != 6)
{
Assert.False(true, "Expected: 4|5|6; actual: " + item.ToString());
}
}
});
Task.WaitAll(tks);
}
示例6: PushTryPop
public void PushTryPop(int producerThreads, int consumerThreads)
{
var bag = new ConcurrentBag<int>();
var startEvent = new ManualResetEventSlim(false);
var finished = 0;
var stop = false;
var producerTasks = Enumerable.Range(0, producerThreads).Select(i => Task.Factory.StartNew(() =>
{
var count = Iterations/producerThreads;
startEvent.Wait();
for (var j = 0; j < count; j++)
bag.Add(0);
Interlocked.Increment(ref finished);
if (finished >= producerThreads) stop = true;
}, TaskCreationOptions.LongRunning)).ToArray();
var consumerTasks = Enumerable.Range(0, consumerThreads).Select(i => Task.Factory.StartNew(() =>
{
int num;
startEvent.Wait();
while (!stop) bag.TryTake(out num);
}, TaskCreationOptions.LongRunning)).ToArray();
var stopwatch = Stopwatch.StartNew();
startEvent.Set();
stop = true;
Task.WaitAll(producerTasks);
Task.WaitAll(consumerTasks);
stopwatch.StopAndLog(Iterations);
}
示例7: RunSuccess
public static void RunSuccess()
{
var conList = new ConcurrentBag<int>();
for (int i = 0; i < 10; i++)
{
conList.Add(i);
}
var task1 = new Task(()=>
{
for (int i = 0; i < 50000; i++)
{
Thread.Sleep(500);
conList.TryTake(out i);
}
});
task1.Start();
var task2 = Task.Factory.StartNew(() =>
{
//此線程取數據后,則不受之前
foreach (var a in conList)
{
Thread.Sleep(1000);
Console.WriteLine("當前線程迭代數據:{0} 外部的集合.Count:{1}", a, conList.Count);
}
});
Task.WaitAll(task1, task2);
Console.WriteLine("OK");
Console.ReadLine();
}
示例8: PickOneTest
public void PickOneTest(int threadCount)
{
Assert.Greater(threadCount, 1);
var testBag = new ConcurrentBag<int>();
var threads = new List<Thread>();
for (var i = 0; i < threadCount; ++i)
{
// ReSharper disable once ObjectCreationAsStatement
// explicit thread generation needed for proper thread safety check
var thd = new Thread(() => { testBag.Add(PrimeNumberTable.PickOne()); });
thd.Start();
threads.Add(thd);
}
foreach (var thd in threads)
thd.Join();
int? itemBefore = null;
Assert.Greater(testBag.Count, 1);
while (!testBag.IsEmpty)
{
int tmp;
if (itemBefore == null)
{
if (testBag.TryTake(out tmp))
itemBefore = tmp;
Assert.NotNull(itemBefore);
}
int? itemNow = null;
if (testBag.TryTake(out tmp))
itemNow = tmp;
else
return;
Assert.NotNull(itemNow);
Assert.AreNotEqual(itemNow, itemBefore);
itemBefore = itemNow;
}
}
示例9: Start
/// <summary>
/// Starts the TCP server loop listening for client connections on the Server Socket, then
/// communicating with the client on that client's TCP Connection Socket.
/// </summary>
public override void Start()
{
ListenSocket = Transport.GetSocket(IPAddress.Any.AddressFamily);
ListenSocket.Bind(IpEndPoint);
ListenSocket.Listen(10);
Console.WriteLine("TCP Server Socket awaiting connection from client");
Console.WriteLine("Press ESC to stop this server");
var shutdownToken = new CancellationTokenSource();
var socketTasks = new ConcurrentBag<Task>();
var serverSocketTask = Task.Run(() =>
{
//loop to listen for TCP connections while token isn't
while (!shutdownToken.IsCancellationRequested)
{
try
{
Console.WriteLine("\r\nTCP Server Socket waiting at {0}", ListenSocket.LocalEndPoint);
var newClientSocket = ListenSocket.Accept();
Connections++;
Console.WriteLine("\r\nConnections: {0}", Connections);
var client = new TcpClientConnection(newClientSocket, Transport.BufferSize);
var clientTask = Task.Factory.StartNew(() =>
{
client.Execute();
Task toRemove;
socketTasks.TryTake(out toRemove); //remove from concurrent bag
Connections--;
Console.WriteLine("\r\nConnections: {0}", Connections);
}, shutdownToken.Token);
socketTasks.Add(clientTask);
}
catch (OperationCanceledException)
{
//time to shutdown
}
}
}, shutdownToken.Token); //cancel this task when token is flagged
socketTasks.Add(serverSocketTask);
//wait for connections
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
}
//no more waiting... shutdown
Console.WriteLine("Stopping... closing open TCP connections");
shutdownToken.CancelAfter(1000); //give tasks 1000ms to finish - then throw them if necessary
Task.WaitAll(socketTasks.ToArray(), 1000); //wait up to 5 seconds for all tasks to end, then give up
Stop();
}
示例10: Run
public void Run()
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
bag.Add(42);
bag.Add(21);
int result;
if (bag.TryTake(out result))
Console.WriteLine(result);
if (bag.TryPeek(out result))
Console.WriteLine("There is a next item: {0}", result);
}
示例11: Example1
private void Example1()
{
ConcurrentBag<int> concurrentBag = new ConcurrentBag<int>();
concurrentBag.Add(21);
concurrentBag.Add(43);
concurrentBag.Add(32);
Console.WriteLine("Initial Concurrent Bag count :" + concurrentBag.Count);
int result;
if (concurrentBag.TryTake(out result))
Console.WriteLine("Concurrent bag count after Take :" + concurrentBag.Count);
if (concurrentBag.TryPeek(out result))
Console.WriteLine("Concurrent bag count after Peek :" + concurrentBag.Count);
}
示例12: GetQualitiesStrings
internal override string[] GetQualitiesStrings(ConcurrentBag<Tuple<double[], double[]>> bag)
{
int size = bag.Count;
string[] output = new string[size];
for (int i = 0; i < size; i++)
{
Tuple<double[], double[]> fst;
bag.TryTake(out fst);
String qualityString = "aW " + fst.Item1[0] + "|aR " + fst.Item1[1] +
"|k " + fst.Item1[2] + "|" + String.Join(",", fst.Item2) + ";";
output[i] = qualityString;
}
return output;
}
示例13: Main
static void Main(string[] args) {
// create a shared collection
ConcurrentBag<int> sharedBag = new ConcurrentBag<int>();
// populate the collection with items to process
for (int i = 0; i < 1000; i++) {
sharedBag.Add(i);
}
// define a counter for the number of processed items
int itemCount = 0;
// create tasks to process the list
Task[] tasks = new Task[10];
for (int i = 0; i < tasks.Length; i++) {
// create the new task
tasks[i] = new Task(() => {
while (sharedBag.Count > 0) {
// define a variable for the dequeue requests
int queueElement;
// take an item from the queue
bool gotElement = sharedBag.TryTake(out queueElement);
// increment the count of items processed
if (gotElement) {
Interlocked.Increment(ref itemCount);
}
}
});
// start the new task
tasks[i].Start();
}
// wait for the tasks to complete
Task.WaitAll(tasks);
// report on the number of items processed
Console.WriteLine("Items processed: {0}", itemCount);
// wait for input before exiting
Console.WriteLine("Press enter to finish");
Console.ReadLine();
}
示例14: Run
public override void Run()
{
var pool = new ThreadwisePool<string>();
var mainClient = pool.GetClient();
// setup a bag of keys to randomly increments
var keys = Enumerable
.Range(0, TotalKeys)
.Select(k => "counter" + k.ToString())
.ToArray();
var keysBag = new ConcurrentBag<string>();
var keySets = TotalTasks / TotalKeys;
for (var i = 0; i < keySets; i++)
foreach (var key in keys)
keysBag.Add(key);
// ensure key is empty
foreach (var key in keys)
mainClient.Del(key);
// increment keys from multiple thread
WriteLine("Incrementing keys: " + string.Join(", ", keys));
Task.WaitAll(Enumerable
.Range(0, TotalTasks)
.Select(n => Task.Factory.StartNew(() =>
{
// obtain a key to increment
string key;
if (!keysBag.TryTake(out key))
WriteLine("ERROR");
// obtain an IRedisClient from the pool
// and use it to INCR a key
var client = pool.GetClient();
client.Incr(key);
}))
.ToArray());
// log result
WriteLine("Result (should be equal):");
foreach (var key in keys)
WriteLine(key + " : " + mainClient.Get(key));
}
示例15: TestPeeking_Scenario_Result
public void TestPeeking_Scenario_Result()
{
ConcurrentBag<object> bag = new ConcurrentBag<object> { 42, 21, 66, 99, 1 ,"joey"};
object result;
bag.Add("Mikey");
if (bag.TryTake(out result))
{
Console.WriteLine(result);
}
if (bag.TryPeek(out result))
{
Console.WriteLine(@"There is a next item: {0}", result);
}
if (bag.TryPeek(out result))
{
Console.WriteLine(@"There is a next item: {0}", result);
}
}