本文整理汇总了C#中ConcurrentBag.TryPeek方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentBag.TryPeek方法的具体用法?C# ConcurrentBag.TryPeek怎么用?C# ConcurrentBag.TryPeek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentBag
的用法示例。
在下文中一共展示了ConcurrentBag.TryPeek方法的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: PopAndPush_CallPopBeforePush_CorrectCouners
public void PopAndPush_CallPopBeforePush_CorrectCouners()
{
ConcurentQueue<int> concurentQueue = new ConcurentQueue<int>(10000);
ConcurrentBag<int> popResult = new ConcurrentBag<int>();
ConcurrentBag<Exception> popResultEx = new ConcurrentBag<Exception>();
ConcurrentBag<int> pushItems = new ConcurrentBag<int>();
Parallel.For(0, 10, i =>
{
pushItems.Add(i);
try
{
var temp = concurentQueue.Pop();
popResult.Add(temp);
}
catch (Exception exp)
{
popResultEx.Add(exp);
}
concurentQueue.Push(i);
});
Exception exception;
popResultEx.TryPeek(out exception);
Assert.IsInstanceOf(typeof(TimeoutException), exception);
Assert.AreEqual(pushItems.Count, popResult.Count + popResultEx.Count);
}
示例3: 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();
}
示例4: 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);
}
示例5: 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);
}
}
示例6: 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);
}
示例7: ConcurrentCollectionTest
//ConcurrentCollectionTest
public static void ConcurrentCollectionTest()
{
ConcurrentBag<string> bag = new ConcurrentBag<string>();
bag.Add("just a test!");
bag.Add("abc");
bag.Add("ARCAS");
string result;
bag.TryPeek(out result);
Console.WriteLine(result);
BlockingCollection<string> collection = new BlockingCollection<string>();
}
示例8: 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);
}
示例9: Main
public static void Main(string[] args)
{
// One thing to keep in mind is that the TryPeek method is not very useful in a multithreaded environment.
// It could be that another thread removes the item before you can access it.
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);
Console.ReadLine();
}
示例10: RTest3_TakeOrPeek
/// <summary>
/// Test bag Take and Peek operations
/// </summary>
/// <param name="bag"></param>
/// <param name="threadsCount"></param>
/// <param name="itemsPerThread"></param>
/// <param name="take"></param>
/// <returns>True if succeeded, false otherwise</returns>
private static void RTest3_TakeOrPeek(ConcurrentBag<int> bag, int threadsCount, int itemsPerThread, bool take)
{
int bagCount = bag.Count;
int succeeded = 0;
int failures = 0;
Task[] threads = new Task[threadsCount];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = Task.Run(() =>
{
for (int j = 0; j < itemsPerThread; j++)
{
int data;
bool result = false;
if (take)
{
result = bag.TryTake(out data);
}
else
{
result = bag.TryPeek(out data);
}
if (result)
{
Interlocked.Increment(ref succeeded);
}
else
{
Interlocked.Increment(ref failures);
}
}
});
}
Task.WaitAll(threads);
if (take)
{
Assert.Equal(bagCount - succeeded, bag.Count);
}
else
{
Assert.Equal(0, failures);
}
}
示例11: RTest2_Add
/// <summary>
/// Test bag addition
/// </summary>
/// <param name="threadsCount"></param>
/// <param name="itemsPerThread"></param>
/// <returns>True if succeeded, false otherwise</returns>
private static void RTest2_Add(int threadsCount, int itemsPerThread)
{
int failures = 0;
ConcurrentBag<int> bag = new ConcurrentBag<int>();
Task[] threads = new Task[threadsCount];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = Task.Run(() =>
{
for (int j = 0; j < itemsPerThread; j++)
{
try
{
bag.Add(j);
int item;
if (!bag.TryPeek(out item) || item != j)
{
Interlocked.Increment(ref failures);
}
}
catch
{
Interlocked.Increment(ref failures);
}
}
});
}
Task.WaitAll(threads);
Assert.Equal(0, failures);
Assert.Equal(itemsPerThread * threadsCount, bag.Count);
}
示例12: Pop_ItemsFromEmptyQueue_CorrectCounters
public void Pop_ItemsFromEmptyQueue_CorrectCounters()
{
ConcurentQueue<int> concurentQueue = new ConcurentQueue<int>(5000);
ConcurrentBag<Exception> popResult = new ConcurrentBag<Exception>();
ConcurrentBag<int> pushItems = new ConcurrentBag<int>();
Parallel.For(0, 10, i =>
{
pushItems.Add(i);
try
{
concurentQueue.Pop();
}
catch (Exception exp)
{
popResult.Add(exp);
}
});
Exception exception;
popResult.TryPeek(out exception);
Assert.IsInstanceOf(typeof(TimeoutException), exception);
Assert.AreEqual(pushItems.Count, popResult.Count);
}
示例13: Cozy
public static void Cozy()
{
Console.WriteLine("\n-----------------------------------------------");
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Console.WriteLine("-----------------------------------------------");
//并发集合
//ConcurrentXXX这些集合都是线程安全的,实现了IProducerConsumerCollection<T>接口
//里面如下的方法
//[__DynamicallyInvokable]
//void CopyTo(T[] array, int index);
//[__DynamicallyInvokable]
//bool TryAdd(T item);
//[__DynamicallyInvokable]
//bool TryTake(out T item);
//[__DynamicallyInvokable]
//T[] ToArray();
//TryXX()方法返回一个bool值,说明操作是否成功
//ConcurrentQueue<T>
var concurrentQueue = new ConcurrentQueue<int>();
concurrentQueue.Enqueue(1);
int i;
var reslut = concurrentQueue.TryPeek(out i);
reslut = concurrentQueue.TryDequeue(out i);
//ConcurrentStack<T>
var concurrentStack = new ConcurrentStack<int>();
concurrentStack.Push(1);
reslut = concurrentStack.TryPeek(out i);
reslut = concurrentStack.TryPop(out i);
//ConcurrentBag<T>
var concurrentBag = new ConcurrentBag<int>();
concurrentBag.Add(1);
reslut = concurrentBag.TryPeek(out i);
reslut = concurrentBag.TryTake(out i);
//ConcurrentDictionary<TKey,TValue>
//该集合没实现IProducerConsumerCollection<T>,因此它的TryXX()是以非堵塞的方式访问成员
var concurrentDictionary = new ConcurrentDictionary<int, int>();
reslut = concurrentDictionary.TryAdd(1, 1);
reslut = concurrentDictionary.TryRemove(1, out i);
//BlockingCollection<T>,该集合的Add()和Taake()会阻塞线程并且一直等待
var blockingCollection = new BlockingCollection<int>();
var events = new ManualResetEventSlim[2];
var waits = new WaitHandle[2];
for (int j = 0; j < events.Length; j++)
{
events[j] = new ManualResetEventSlim(false);
waits[j] = events[j].WaitHandle;
}
new Thread(() =>
{
for (int j = 0; j < 300; j++)
{
blockingCollection.Add(j);
}
events[0].Set();
}).Start();
new Thread(() =>
{
for (int j = 0; j < 300; j++)
{
blockingCollection.Take();
}
events[1].Set();
}).Start();
if (!WaitHandle.WaitAll(waits))
{
Console.WriteLine("wait failed");
}
else
{
Console.WriteLine("reading/writing finished");
}
}
示例14: RunConcurrentBagTest3_TakeOrPeek
/// <summary>
/// Test bag Take and Peek operations
/// </summary>
/// <param name="bag"></param>
/// <param name="threadsCount"></param>
/// <param name="itemsPerThread"></param>
/// <param name="take"></param>
/// <returns>True if succeeded, false otherwise</returns>
private static bool RunConcurrentBagTest3_TakeOrPeek(ConcurrentBag<int> bag, int threadsCount, int itemsPerThread, bool take)
{
TestHarness.TestLog("* RunConcurrentBagTest3_TakeOrPeek(" + threadsCount + "," + itemsPerThread + ")");
int bagCount = bag.Count;
int succeeded = 0;
int failures = 0;
Thread[] threads = new Thread[threadsCount];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(() =>
{
for (int j = 0; j < itemsPerThread; j++)
{
try
{
int data;
bool result = false;
if (take)
{
result = bag.TryTake(out data);
}
else
{
result = bag.TryPeek(out data);
}
if (result)
{
Interlocked.Increment(ref succeeded);
}
else
{
Interlocked.Increment(ref failures);
}
}
catch
{
Interlocked.Increment(ref failures);
}
}
});
threads[i].Start();
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
if (take)
{
if (bag.Count != bagCount - succeeded)
{
TestHarness.TestLog("TryTake failed, the remaing count doesn't match the expected count");
return false;
}
}
else if (failures > 0)
{
TestHarness.TestLog("TryPeek failed, Unexpected exceptions has been thrown");
return false;
}
TestHarness.TestLog("Try Take/peek succeeded");
return true;
}
示例15: ProcessFrame
//.........这里部分代码省略.........
{
// Sequential mode. Scan the integral image searching
// for objects in the window without parallelization.
// For every pixel in the window column
for (int y = 0; y < yEnd; y += yStep)
{
window.Y = y;
// For every pixel in the window row
for (int x = 0; x < xEnd; x += xStep)
{
window.X = x;
if (searchMode == ObjectDetectorSearchMode.NoOverlap && overlaps(window))
continue; // We have already detected something here, moving along.
// Try to detect and object inside the window
if (classifier.Compute(integralImage, window))
{
// an object has been detected
detectedObjects.Add(window);
if (searchMode == ObjectDetectorSearchMode.Single)
goto EXIT; // Stop on first object found
}
}
}
}
else
{
// Parallel mode. Scan the integral image searching
// for objects in the window with parallelization.
ConcurrentBag<Rectangle> bag = new ConcurrentBag<Rectangle>();
int numSteps = (int)Math.Ceiling((double)yEnd / yStep);
// For each pixel in the window column
Parallel.For(0, numSteps, (j, options) =>
{
int y = j * yStep;
// Create a local window reference
Rectangle localWindow = window;
localWindow.Y = y;
// For each pixel in the window row
for (int x = 0; x < xEnd; x += xStep)
{
if (options.ShouldExitCurrentIteration) return;
localWindow.X = x;
// Try to detect and object inside the window
if (classifier.Compute(integralImage, localWindow))
{
// an object has been detected
bag.Add(localWindow);
if (searchMode == ObjectDetectorSearchMode.Single)
options.Stop();
}
}
});
// If required, avoid adding overlapping objects at
// the expense of extra computation. Otherwise, only
// add objects to the detected objects collection.
if (searchMode == ObjectDetectorSearchMode.NoOverlap)
{
foreach (Rectangle obj in bag)
if (!overlaps(obj)) detectedObjects.Add(obj);
}
else if (searchMode == ObjectDetectorSearchMode.Single)
{
if (bag.TryPeek(out window))
{
detectedObjects.Add(window);
goto EXIT;
}
}
else
{
foreach (Rectangle obj in bag)
detectedObjects.Add(obj);
}
}
}
EXIT:
Rectangle[] objects = detectedObjects.ToArray();
checkSteadiness(objects);
lastObjects = objects;
return objects; // Returns the array of detected objects.
}