本文整理汇总了C#中ConcurrentQueue.Count方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentQueue.Count方法的具体用法?C# ConcurrentQueue.Count怎么用?C# ConcurrentQueue.Count使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentQueue
的用法示例。
在下文中一共展示了ConcurrentQueue.Count方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: QuickPulseQuotaTrackerIsThreadSafe
public void QuickPulseQuotaTrackerIsThreadSafe()
{
// ARRANGE
int maxQuota = 100 * 60;
int experimentLengthInSeconds = 1000;
int concurrency = 1000;
var mockTimeProvider = new ClockMock();
var quotaTracker = new QuickPulseQuotaTracker(mockTimeProvider, maxQuota, 0);
var quotaApplicationResults = new ConcurrentQueue<bool>();
// ACT
for (int i = 0; i < experimentLengthInSeconds; i++)
{
mockTimeProvider.FastForward(TimeSpan.FromSeconds(1));
var tasks = new List<Action>();
for (int j = 0; j < concurrency; j++)
{
tasks.Add(() => quotaApplicationResults.Enqueue(quotaTracker.ApplyQuota()));
}
Parallel.Invoke(new ParallelOptions() { MaxDegreeOfParallelism = concurrency }, tasks.ToArray());
}
// ASSERT
var passedQuotaCount = quotaApplicationResults.Count(result => result);
var correctResult = maxQuota / 60 * experimentLengthInSeconds;
Assert.AreEqual(correctResult, passedQuotaCount);
Assert.IsFalse(quotaTracker.ApplyQuota());
}
示例2: DoesNotDispatchMessageWithNullBus
public void DoesNotDispatchMessageWithNullBus()
{
var busInstances = new ConcurrentQueue<IBus>();
using (var activator = new BuiltinHandlerActivator())
{
activator.Handle<string>(async (bus, message) =>
{
busInstances.Enqueue(bus);
});
Configure.With(activator)
.Logging(l => l.ColoredConsole(LogLevel.Warn))
.Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "race-condition"))
.Options(o =>
{
o.SetNumberOfWorkers(1);
o.SetMaxParallelism(1);
})
.Start();
Task.WaitAll(Enumerable.Range(0, 1000)
.Select(i => activator.Bus.SendLocal($"message-{i}"))
.ToArray());
}
Thread.Sleep(1000);
var numberOfNulls = busInstances.Count(i => i == null);
Assert.That(numberOfNulls, Is.EqualTo(0),
"Did not expect any messages to be dispatched with a NULL bus instance");
}
示例3: 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));
}
}
示例4: TestEtw
public void TestEtw()
{
using (var listener = new TestEventListener(new Guid("159eeeec-4a14-4418-a8fe-faabcd987887"), EventLevel.Verbose))
{
var events = new ConcurrentQueue<int>();
listener.RunWithCallback(ev => events.Enqueue(ev.EventId), () => {
Enumerable.Range(0, 10000).AsParallel().Select(i => i).ToArray();
});
const int BeginEventId = 1;
Assert.Equal(expected: 1, actual: events.Count(i => i == BeginEventId));
const int EndEventId = 2;
Assert.Equal(expected: 1, actual: events.Count(i => i == EndEventId));
const int ForkEventId = 3;
const int JoinEventId = 4;
Assert.True(events.Count(i => i == ForkEventId) > 0);
Assert.Equal(events.Count(i => i == ForkEventId), events.Count(i => i == JoinEventId));
}
}
示例5: OutputCountItem
public void OutputCountItem(ConcurrentBag<Task> tasks, ConcurrentQueue<int> concurrentQueue)
{
Console.WriteLine();
foreach (var task in tasks.OrderBy(id => id.Id))
{
Console.WriteLine("Поток № {0} - количество элементов в контейнере {1}",
task.Id, concurrentQueue.Count(x => x == task.Id));
}
Console.WriteLine("\nВсего в контейнере {0} элементов. ",
concurrentQueue.Count);
Console.ReadKey();
}
示例6: SemaphoreMultiplex
static void SemaphoreMultiplex()
{
counter = 0;
Semaphore multiple = new Semaphore(0, 10);
multiple.Release();
ConcurrentQueue<int> answer = new ConcurrentQueue<int>();
//multiple.
Random ex = new Random();
Thread[] array = new Thread[50];
for (int i = 0; i < 50; i++)
{
array[i] = new Thread(
() =>
{
multiple.WaitOne();
counter = 1 + counter;
Thread.Sleep(ex.Next(67));
multiple.Release();
answer.Enqueue(counter);
}
);
array[i].Start();
}
foreach (var t in array)
{
t.Join();
}
var s = answer.Distinct();
foreach (var t in answer)
{
Console.WriteLine("count {0} and t {1}", t, answer.Count());
};
}
示例7: BwBusiness_DoWork
private void BwBusiness_DoWork(object sender, DoWorkEventArgs e)
{
Stopwatch directoryStopwatch = new Stopwatch();
threadCount++;
do
{
//Get available memory
var computerInfo = new ComputerInfo();
var availablePhysicalMemory = (decimal)(computerInfo.AvailablePhysicalMemory);
var totalPhysicalMemory = (decimal)(computerInfo.TotalPhysicalMemory);
var freeMemRatio = availablePhysicalMemory / totalPhysicalMemory;
//Memory protection check
if (freeMemRatio > (decimal).09)
{
bool errorFlag = false;
if (!directoryStopwatch.IsRunning)
{
directoryStopwatch.Start();
}
//Get file info so that any necessary logging can be written to the
//appropriate folder
FileInfo fiPeek;
fileQueue.TryPeek(out fiPeek);
try
{
Stopwatch swFile = new Stopwatch();
swFile.Start();
bool isCR2Processing = false;
//Keep trying to get a file from the queue
FileInfo fi;
while (!fileQueue.TryDequeue(out fi) && fileQueue.Count() != 0)
{
}
if (fi != null && File.Exists(fi.FullName))
{
string filePath = fi.FullName;
string directoryPath = fi.DirectoryName;
currentDirectory = directoryPath;
//Create Subfolders for Processed DNGs and Logs
if (fi.Name.ToLower().Contains(".dng"))
{
fi.Directory.CreateSubdirectory("Dual ISO DNG");
}
if (fi.Name.ToLower().Contains(".cr2"))
{
isCR2Processing = true;
fi.Directory.CreateSubdirectory("Dual ISO CR2");
fi.Directory.CreateSubdirectory("Dual ISO Original CR2");
}
fi.Directory.CreateSubdirectory("logs");
//Handle condition where application exited before files moved
if (File.Exists(fi.FullName.ToLower().Replace(".dng", ".cr2")))
{
isCR2Processing = true;
}
//Get initial image path pre-move
string initialImagePath = fi.FullName;
//Get initial log path pre-move
string initialLogPath = initialImagePath + ".log";
//Get log directory path
string logDirectoryPath = fi.Directory.EnumerateDirectories().Where(
d => d.Name.Contains("logs")).FirstOrDefault().FullName;
//Get destination log path
string destLogPath = fi.Directory.EnumerateDirectories().Where(
d => d.Name.Contains("logs")).FirstOrDefault().FullName + "\\" + fi.Name + ".log";
//Get destination image path
string destImagePath = string.Empty;
if (fi.Name.ToLower().Contains(".dng"))
{
if (!isCR2Processing)
{
destImagePath = fi.Directory.EnumerateDirectories().Where(
d => d.Name.Contains("Dual ISO DNG")).FirstOrDefault().FullName + "\\" + fi.Name;
}
else
{
destImagePath = fi.Directory.EnumerateDirectories().Where(
d => d.Name.Contains("Dual ISO CR2")).FirstOrDefault().FullName + "\\" + fi.Name;
}
}
else if (fi.Name.ToLower().Contains(".cr2"))
{
destImagePath = fi.Directory.EnumerateDirectories().Where(
d => d.Name.Contains("Dual ISO Original CR2")).FirstOrDefault().FullName + "\\" + fi.Name;
}
//.........这里部分代码省略.........
示例8: BwPreparing_DoWork
private void BwPreparing_DoWork(object sender, DoWorkEventArgs e)
{
preparing = true;
process = "Preparing";
swPreparing.Start();
DirectoryInfo di = new DirectoryInfo(txtImageFolderPath.Text);
Stopwatch diListStopwatch = new Stopwatch();
Stopwatch fileListStopwatch = new Stopwatch();
//Prepare and Setup File Queues for Processing
if (di.Exists)
{
try
{
//Build Directory Queue
diListStopwatch.Start();
IEnumerable<DirectoryInfo> diList = di.EnumerateDirectories("*", SearchOption.AllDirectories).Where(
d => d.EnumerateFiles("*.dng", SearchOption.TopDirectoryOnly).Union(d.EnumerateFiles("*.cr2",
SearchOption.TopDirectoryOnly)).Count() > 0 && !d.Name.Contains("Dual ISO DNG") && !d.Name.Contains("Dual ISO CR2") &&
!d.Name.Contains("Dual ISO Original CR2") && !d.Name.Contains("logs"));
dirQueue = new ConcurrentQueue<DirectoryInfo>(diList);
//How many directories in play?
maxDirQueueCount = dirQueue.Count;
diListStopwatch.Stop();
//How long did it take to get a directory listing and build dir queue?
string diListDuration = diListStopwatch.Elapsed.ToString();
//Build File Queue
fileListStopwatch.Start();
List<FileInfo> fileList = new List<FileInfo>();
//Search root level for files
fileList.AddRange(di.EnumerateFiles("*.dng", SearchOption.TopDirectoryOnly).Union(di.EnumerateFiles("*.cr2",
SearchOption.TopDirectoryOnly)).ToList());
//Search subdirectories for files
foreach (DirectoryInfo dInfo in diList)
{
string path = dInfo.FullName;
fileList.AddRange(dInfo.EnumerateFiles("*.dng", SearchOption.TopDirectoryOnly).Union(dInfo.EnumerateFiles("*.cr2",
SearchOption.TopDirectoryOnly)).ToList());
DirectoryInfo dInfoDequeue;
dirQueue.TryDequeue(out dInfoDequeue);
}
fileQueue = new ConcurrentQueue<FileInfo>(fileList);
//How many files in play?
maxFileQueueCount = fileQueue.Count;
//Get file count for first folder being processed
if (maxFileQueueCount > 0)
{
FileInfo subfolderFileInfo;
fileQueue.TryPeek(out subfolderFileInfo);
if (subfolderFileInfo != null)
{
subFolderFileQueue = new ConcurrentQueue<FileInfo>(
subfolderFileInfo.Directory.EnumerateFiles("*.dng", SearchOption.TopDirectoryOnly).Union(
subfolderFileInfo.Directory.EnumerateFiles("*.cr2", SearchOption.TopDirectoryOnly)).ToList()
);
maxSubfolderFileQueueCount = subFolderFileQueue.Count();
}
}
fileListStopwatch.Stop();
//How long did it take to get all file listings and build file queue?
string fileListDuration = fileListStopwatch.Elapsed.ToString();
btnBusiness_Click(this, new EventArgs());
}
catch (Exception ex)
{
if (di != null)
{
File.WriteAllText(di.FullName + "\\ExceptionLog." + Guid.NewGuid().ToString() + ".log", ex.Message + "\r\n" + ex.StackTrace);
}
}
}
else
{
BeginInvoke((MethodInvoker)delegate
{
FindAndMoveMsgBox("Path Error", this);
MessageBox.Show(this, "Image Folder Path Invalid", "Path Error");
});
}
e.Cancel = true;
}
示例9: FillPageQueue
public int FillPageQueue(bool OnlyLarge = false)
{
PageQueue = new ConcurrentQueue<PFN>();
VIRTUAL_ADDRESS VA;
VA.Address = 0;
if (DP.PT == null)
PageTable.AddProcess(DP, DP.MemAccess);
//Parallel.ForEach(DP.TopPageTablePage, (kvp) =>
foreach (var kvp in DP.TopPageTablePage)
{
// were at the top level (4th)
VA.PML4 = kvp.Key;
var pfn = new PFN { PTE = kvp.Value, VA = new VIRTUAL_ADDRESS(VA.PML4 << 39) };
foreach (var DirectoryPointerOffset in DP.PT.ExtractNextLevel(pfn, true, 3))
{
if (DirectoryPointerOffset == null) continue;
foreach (var DirectoryOffset in DP.PT.ExtractNextLevel(DirectoryPointerOffset, KernelSpace, 2))
{
if (DirectoryOffset == null) continue;
// if we have a large page we add it now
if (DirectoryOffset.PTE.LargePage)
PageQueue.Enqueue(DirectoryOffset);
// otherwise were scanning lower level entries
else if(!OnlyLarge)
{
foreach (var TableOffset in DP.PT.ExtractNextLevel(DirectoryOffset, KernelSpace, 1))
{
if (TableOffset == null) continue;
PageQueue.Enqueue(TableOffset);
}
}
}
}
}
//});
return PageQueue.Count();
}
示例10: InsertData
public static void InsertData(DataSet dataSet)
{
if (dataSet == null)
throw new ArgumentNullException("DataSet param is null");
try
{
//ConcurrentDictionary<string, object> cache = new ConcurrentDictionary<string, object>();
ICacheManager cache = new MemoryCacheManager();
var exceptions = new ConcurrentQueue<Exception>();
List<Task> tasks = new List<Task>();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
using (var container = new ModelsContainer())
{
foreach (DataTable dt in dataSet.Tables)
{
//Task task = Task.Factory.StartNew(() =>
//{
try
{
Console.WriteLine("----------Table name is : {0}---------", dt.TableName);
int cursor = 0;
foreach (DataRow dr in dt.Rows)
{
Record record = new Record();
string brandsName = dr[0].ToString();
var brands = cache.Get<Brands>(brandsName, () =>
{
return new Brands() { Name = brandsName };
});
record.Brands = brands;
string modelsName = dr[1].ToString();
var models = cache.Get<Models>(modelsName, () =>
{
return new Models() { Name = modelsName };
});
record.Models = models;
record.City = dr[2].ToString();
string dv = dr[3].ToString().Replace(".", "");
string d = string.Format("{0}-{1}-01", dv.Substring(0, 4), dv.Substring(4, 2)).Trim();
var buyYear = cache.Get<BuyYear>(d, () =>
{
return new BuyYear() { Time = Convert.ToDateTime(d) };
});
record.BuyYear = buyYear;
d = string.Format("{0}-01-01", dr[4].ToString());
record.Both = DateTime.Parse(d);
bool g = dr[5].ToString().Equals("男") ? true : false;
record.Gender = Convert.ToBoolean(g);
record.Address = dr[6].ToString();
record.Zip = dr[7].ToString();
container.Set<Record>().Add(record);
Console.WriteLine("address {0}, cursor = {1}, threadId = {2}", record.Address, cursor, Thread.CurrentThread.ManagedThreadId);
cursor++;
if (cursor == 100)
{
cursor = 0;
container.SaveChanges();
}
}
}
catch (Exception ex)
{
exceptions.Enqueue(ex);
}
//});
//tasks.Add(task);
container.SaveChanges();
}
}
//Task.WaitAll(tasks.ToArray());
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
if (exceptions.Any())
{
Console.WriteLine("Parallel have exceptions, count = {0}", exceptions.Count());
}
}
catch (Exception ex)
{
string msg = ex.OutputMessage();
Console.WriteLine("{0}", msg);
}
}
示例11: SensorCloudPusher
public SensorCloudPusher(int deviceId)
{
this.DPDeviceID = deviceId;
using (var dbContext = new DynapowerCloudMonitoringDbContext())
{
var DPDevice = dbContext.Devices.Find(this.DPDeviceID);
if (DPDevice == null)
{
throw new Exception("Unknown Dynapower Device");
}
this.SensorCloudDeviceID = DPDevice.SensorCloudSettings.DeviceID;
this.SensorCloudAPIKey = DPDevice.SensorCloudSettings.APIKey;
var device = getDevice();
var sensor = addSensor(device, DPDevice);
var exceptions = new ConcurrentQueue<Exception>();
Parallel.ForEach(DPDevice.Registers, reg =>
{
try
{
var channelID = reg.RegisterNumber.ToString();
var channelDesc = reg.Description;
var channelLabel = reg.Alias;
addChannel(sensor, channelID, channelLabel, channelDesc);
}
catch (Exception ex)
{
exceptions.Enqueue(ex);
}
});
if (exceptions.Count() > 0)
{
throw new AggregateException(exceptions);
}
}
_initialized = true;
}
示例12: pushAllData
public void pushAllData(IEnumerable<ChannelDataPoints> dataAndChannels)
{
Logger.LogMessageToDB("Attempting to push data to SensorCloud.");
checkInit();
if (dataAndChannels.Count() == 0)
{
return;
}
var device = getDevice();
var sensor = getSensor(device);
var exceptionQueue = new ConcurrentQueue<Exception>();
Parallel.ForEach(dataAndChannels, dataAndChannel =>
{
try
{
var channel = getChannel(sensor, dataAndChannel.ChannelID);
channel.AddTimeSeriesData(_sampleRate, dataAndChannel.DataPoints);
}
catch (Exception ex)
{
exceptionQueue.Enqueue(ex);
}
});
if (exceptionQueue.Count() > 0)
{
throw new AggregateException(exceptionQueue);
}
else
{
Logger.LogMessageToDB("Data Successfully Pushed To SensorCloud.");
}
}