本文整理汇总了C#中ConcurrentStack类的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentStack类的具体用法?C# ConcurrentStack怎么用?C# ConcurrentStack使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ConcurrentStack类属于命名空间,在下文中一共展示了ConcurrentStack类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExclusiveConnectionStrategy
/// <summary>
/// Initializes the strategy with the specified nodes and cluster configuration
/// </summary>
/// <param name="nodes"> The nodes. </param>
/// <param name="config"> The config. </param>
public ExclusiveConnectionStrategy(Ring nodes, ClusterConfig config)
{
_nodes = nodes;
_config = config;
_connections = new ConcurrentStack<Connection>();
_rndGen = new Random((int)DateTime.Now.Ticks);
}
示例2: Main
static void Main(string[] args)
{
//Stack - Pilha (LIFO)
ConcurrentStack<int> stack = new ConcurrentStack<int>();
//Adiciona um item na pilha
stack.Push(42);
int result;
//metodo trypop retorna o ultimo item a ser adicionado na lista, caso não tenha mais item ele não dar por que ele "tenta(try)" pega um item
//quando usar o metodo trypop o item é removido da coleção
if (stack.TryPop(out result))
{
Console.WriteLine("Popped: {0}", result);
}
if (stack.TryPop(out result))
{
Console.WriteLine("Popped: {0}", result);
}
stack.PushRange(new int[] { 1, 2, 3 });
int[] values = new int[2];
//metod retorna uma coleção de itens da pilha
stack.TryPopRange(values);
foreach (var item in values)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
示例3: FileHistoryService
public FileHistoryService()
{
_storage = "recent.dat";
_basePath = Path.GetDirectoryName(typeof(FileHistoryService).Assembly.Location);
_container = new ConcurrentStack<string>();
//InitializeFromFile();
}
示例4: SocketSniffer
public SocketSniffer(NetworkInterfaceInfo nic, Filters<IPPacket> filters, IOutput output)
{
this.outputQueue = new BlockingCollection<TimestampedData>();
this.filters = filters;
this.output = output;
this.bufferManager = new BufferManager(BUFFER_SIZE, MAX_RECEIVE);
this.receivePool = new ConcurrentStack<SocketAsyncEventArgs>();
var endPoint = new IPEndPoint(nic.IPAddress, 0);
// IPv4
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
this.socket.Bind(endPoint);
this.socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
// Enter promiscuous mode
try
{
this.socket.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), new byte[4]);
}
catch (Exception ex)
{
Console.WriteLine("Unable to enter promiscuous mode: {0}", ex);
throw;
}
}
示例5: Should_Succeed_With_Multiple_Rpc_Calls_At_The_Same_Time
public async Task Should_Succeed_With_Multiple_Rpc_Calls_At_The_Same_Time()
{
/* Setup */
var payloads = new List<Guid> { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
var uniqueResponse = new ConcurrentStack<Guid>(payloads);
var requester = BusClientFactory.CreateDefault();
var responder = BusClientFactory.CreateDefault();
responder.RespondAsync<BasicRequest, BasicResponse>((req, i) =>
{
Guid payload;
if (!uniqueResponse.TryPop(out payload))
{
Assert.True(false, "No entities in stack. Try purgin the response queue.");
};
return Task.FromResult(new BasicResponse { Payload = payload });
});
/* Test */
var first = requester.RequestAsync<BasicRequest, BasicResponse>(new BasicRequest { Number = 1 });
var second = requester.RequestAsync<BasicRequest, BasicResponse>(new BasicRequest { Number = 2 });
var third = requester.RequestAsync<BasicRequest, BasicResponse>(new BasicRequest { Number = 3 });
Task.WaitAll(first, second, third);
/* Assert */
Assert.Contains(first.Result.Payload, payloads);
Assert.Contains(second.Result.Payload, payloads);
Assert.Contains(third.Result.Payload, payloads);
Assert.NotEqual(first.Result.Payload, second.Result.Payload);
Assert.NotEqual(second.Result.Payload, third.Result.Payload);
Assert.NotEqual(first.Result.Payload, third.Result.Payload);
}
示例6: verify_bahaviour_for_concurrent_access_under_identical_keys
public void verify_bahaviour_for_concurrent_access_under_identical_keys()
{
var keys = new[] {"a", "a"};
var counter = new ConcurrentStack<int>();
var storage = new ConcurrentStack<TestItem>();
// first run
var threads = MakeThreads(keys);
threads.ForEach(t => t.Start(new object[] {storage, counter}));
threads.ForEach(t => t.Join());
Assert.Equal(1, counter.Count);
Assert.Equal(2, storage.Count);
var a = storage.First();
Assert.Same(storage.First(), storage.Last());
// cleanups and second run
storage.Clear();
counter.Clear();
threads = MakeThreads(keys);
threads.ForEach(t => t.Start(new object[] {storage, counter}));
threads.ForEach(t => t.Join());
Assert.Equal(0, counter.Count);
Assert.Equal(2, storage.Count);
var aa = storage.First();
Assert.Same(storage.First(), storage.Last());
Assert.Same(a, aa);
}
示例7: ConnectionWorkersPool
public ConnectionWorkersPool(
uint numbersOfBuffers, uint buffersSize, Action<object, SocketAsyncEventArgs> ioCompleted,
IRequestProcessorFactory requestProcessorFactory)
{
_buffersSize = buffersSize;
_numbersOfBuffers = numbersOfBuffers;
_connectionWorkers = new ConcurrentStack<ConnectionWorker>();
for (var i = 0; i < numbersOfBuffers; i++)
{
var buffer = new byte[buffersSize];
for (var j = 0; j < buffer.Length; j++)
{
buffer[j] = (byte)j;
}
var connectionWorker = new ConnectionWorker
{
RequestProcessor = requestProcessorFactory.GetRequestProcessor()
};
var readWriteAsync = new SocketAsyncEventArgs {UserToken = connectionWorker};
connectionWorker.SocketAsyncEventArgs = readWriteAsync;
readWriteAsync.Completed += new EventHandler<SocketAsyncEventArgs>(ioCompleted);
_connectionWorkers.Push(connectionWorker);
}
}
示例8: TestMultiplex
static void TestMultiplex()
{
counter = 0;
ThreadMultiplex multiplex = new ThreadMultiplex(100);
Random exec = new Random();
Thread[] threadArray = new Thread[1000];
ConcurrentStack<int> answer = new ConcurrentStack<int>();
for (int i = 0; i < 1000; i++)
{
int temp = -1;
threadArray[i] = new Thread(
()=>{
multiplex.Enter();
Thread.Sleep(exec.Next(576));
temp = ++counter;
multiplex.Release();
Thread.Sleep(exec.Next(146));
answer.Push(temp);
}
);
threadArray[i].Start();
//Console.WriteLine(temp);
}
foreach (var t in threadArray)
{
t.Join();
}
foreach(var t in answer)
{
Console.WriteLine(t);
}
}
示例9: verify_bahaviour_for_concurrent_access_under_different_keys
public void verify_bahaviour_for_concurrent_access_under_different_keys()
{
var keys = new[] {"a", "b"};
var counter = new ConcurrentStack<int>(); // value factory threads
var storage = new ConcurrentStack<TestItem>(); // cached items
// first run
var threads = MakeThreads(keys);
threads.ForEach(t => t.Start(new object[] {storage, counter}));
threads.ForEach(t => t.Join());
Assert.Equal(2, counter.Count);
Assert.Equal(2, storage.Count);
Assert.NotSame(storage.First(), storage.Last());
var a = storage.FirstOrDefault(x => x.Id == "a");
var b = storage.FirstOrDefault(x => x.Id == "b");
// cleanups and second run
storage.Clear();
counter.Clear();
threads = MakeThreads(keys);
threads.ForEach(t => t.Start(new object[] {storage, counter}));
threads.ForEach(t => t.Join());
Assert.Equal(0, counter.Count);
Assert.Equal(2, storage.Count);
Assert.NotSame(storage.First(), storage.Last());
var aa = storage.FirstOrDefault(x => x.Id == "a");
var bb = storage.FirstOrDefault(x => x.Id == "b");
Assert.Same(a, aa);
Assert.Same(b, bb);
}
示例10: TestBasicScenarios
public static void TestBasicScenarios()
{
ConcurrentStack<int> cs = new ConcurrentStack<int>();
cs.Push(1);
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
cs.Push(2);
cs.Push(3);
cs.Push(4);
});
tks[1] = Task.Run(() =>
{
int item1, item2;
var ret1 = cs.TryPop(out item1);
// at least one item
Assert.True(ret1);
var ret2 = cs.TryPop(out item2);
// two item
if (ret2)
{
Assert.True(item1 > item2, String.Format("{0} should greater than {1}", item1, item2));
}
else // one item
{
Assert.Equal(1, item1);
}
});
Task.WaitAll(tks);
}
示例11: generatePaths
//simulate sim;
//simulateHist simHist;
public ConcurrentBag<double> generatePaths(double initialPrice, int numberOfPaths, double timeToExpiry)
{
ConcurrentBag<double> toReturn = new ConcurrentBag<double>{};
//var indices = Enumerable.Range(0, numberOfPaths);
var rnd = new Random(42);
ConcurrentStack<int> seeds = new ConcurrentStack<int> {};
for (int i = 0; i < numberOfPaths; ++i)
seeds.Push(rnd.Next(1, numberOfPaths - 1));
int steps = Convert.ToInt32 (Math.Floor(timeToExpiry / bm.deltaT));
Parallel.ForEach(seeds,
//new ParallelOptions { MaxDegreeOfParallelism = 2 },
seed =>
{
Thread.Sleep(1);
simulate mySim = new simulate(simulator.simulate);
double res = new double();
res = mySim(steps, initialPrice, seed, bm);
toReturn.Add(res);
}
);
return toReturn;
}
示例12: PushTryPop
public void PushTryPop(int producerThreads, int consumerThreads)
{
var stack = new ConcurrentStack<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++)
stack.Push(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) stack.TryPop(out num);
}, TaskCreationOptions.LongRunning)).ToArray();
var stopwatch = Stopwatch.StartNew();
startEvent.Set();
stop = true;
Task.WaitAll(producerTasks);
Task.WaitAll(consumerTasks);
stopwatch.StopAndLog(iterations);
}
示例13: BufferManager
public BufferManager(int totalBytes, int totalBufferBytesInEachSaeaObject)
{
_totalBytesInBufferBlock = totalBytes;
_currentIndex = 0;
_bufferBytesAllocatedForEachSaea = totalBufferBytesInEachSaeaObject;
_freeIndexPool = new ConcurrentStack<int>();
}
示例14: Setup
public void Setup()
{
stack = new ConcurrentStack<int>();
for (int i = 0; i < 10; i++) {
stack.Push(i);
}
}
示例15: Main
static void Main(string[] args)
{
ConcurrentStack<int> stack = new ConcurrentStack<int>();
stack.Push(42);
int result;
if (stack.TryPop(out result))
{
Console.WriteLine(result);
}
stack.PushRange(new int[] { 1, 2, 3 });
int[] values = new int[2];
stack.TryPopRange(values);
foreach (var i in values)
{
Console.WriteLine(i);
}
Console.Write("Press a key to exit");
Console.ReadKey();
}