public void ThreadSafeQueueTest() { var q = new ThreadSafeQueue<string>(); var methodFill = new WaitCallback(s => { for (var i = 0; i < 33; i++) { Assert.IsTrue(q.InQueue("iter" + i, 1000)); Thread.Sleep(20); } }); var methodFlush = new WaitCallback(s => { var countRead = 0; for (var i = 0; i < 40; i++) { bool timeout; var items = q.ExtractAll(1000, out timeout); countRead += items.Count; Thread.Sleep(20); } Assert.IsTrue(countRead > 0); }); ThreadPool.QueueUserWorkItem(methodFill); ThreadPool.QueueUserWorkItem(methodFlush); }
public WorkGenerator(ref ThreadSafeQueue<Node> queueToAddWorkTo, ref ThreadSafeQueue<RenderLine> renderLines, ref Tuple<int, int, int> blockOffset, Node[] block) { _block = block; _blockOffset = blockOffset; _clientWorkQueue = queueToAddWorkTo; _clientRenderQueue = renderLines; }
private static void DoTest() { ThreadSafeQueue<int> queue = new ThreadSafeQueue<int>(); Task producerTask1 = new Task(() => DoProduce(queue)); Task producerTask2 = new Task(() => DoProduce(queue)); Task consumerTask1 = new Task(() => DoCunsume(queue)); Task consumerTask2 = new Task(() => DoCunsume(queue)); Task consumerTask3 = new Task(() => DoCunsume(queue)); Array.ForEach(new[] { producerTask1, producerTask2, consumerTask1, consumerTask2, consumerTask3 }, x => x.Start()); Task.WaitAll(producerTask1, producerTask2, consumerTask1, consumerTask2, consumerTask3); Console.WriteLine("Produced: {0}", queue.ProducedCount); Console.WriteLine("Consumed: {0}", queue.ConsumedCount); }
/// constructor /// public WatchLists(APPLICATION_DATA appData) { try { // load stored data mapURL = UserSettings.Get(UserSettingTags.GPSMAPURL); if (mapURL == null) mapURL = "http://maps.google.com/maps?q="; m_AppData = appData; m_Log = (ErrorLog)m_AppData.Logger; m_AppData.AddOnClosing(Stop, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.WatchList.WatchList_LastAlert].StatString.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.WatchList.WatchList_NumAlerts].Accumulator.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.WatchList.Watchlist_NumListsLoaded].Accumulator.RegisterForUse(true); m_Stop = false; m_NewLPRResultQ = new ThreadSafeQueue<FRAME>(60); m_AlertsToBeGeneratedQ = new ThreadSafeQueue<FRAME>(60); m_SettingsTags = new WatchListDynamicTags(); m_LoadListSingleton = new object(); m_WatchLists = LoadListsFromUserConfig(); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.WatchList.Watchlist_NumListsLoaded].Accumulator.SetValue = m_WatchLists.Count; } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } }
/// <summary> /// </summary> public QueuedIndexRunner(ThreadSafeQueue<Node> _queueOfNodesToIndex, ManualResetEvent _threadResetMonitor, INodeIndexer _nodeIndexer, string _labelRole) { this._queueOfNodesToIndex = _queueOfNodesToIndex; this._labelRole = _labelRole; this._nodeIndexer = _nodeIndexer; this._threadResetMonitor = _threadResetMonitor; }
public TransactionalCommandRunner(IBackgroundWorker backgroundWorker, ThreadSafeQueue<ICommand> queue) { _commandQueue = queue; _bgWorker = backgroundWorker; _undoStack = new Stack<ICommand>(); _workReportCreator = new WorkReportGenerator(); _cancelRequested = false; }
public EmailServices(APPLICATION_DATA appData) { m_AppData = appData; m_AppData.AddOnClosing(Stop, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_Log = (ErrorLog) m_AppData.Logger; m_SendMessagesQ = new ThreadSafeQueue<SEND_MESSAGE>(40); m_SendResultEvents = new ThreadSafeHashTable(40); m_SendResultQ = new ThreadSafeQueue<SEND_RESULT>(40); }
public void AddQueue(ThreadSafeQueue<RenderLine> workQueue) { using (var locked = workQueue.Lock()) { while (locked.Count > 0) { lineQueue.Enqueue(locked.Dequeue()); } } }
/// Constructor for server-side session. public LoopbackSession(LoopbackSession remoteSession, LoopbackPipe entry) : base(entry.Acceptor) { Config = new DefaultLoopbackSessionConfig(); _lock = remoteSession._lock; _localEP = remoteSession._remoteEP; _remoteEP = remoteSession._localEP; _filterChain = new LoopbackFilterChain(this); _remoteSession = remoteSession; _receivedMessageQueue = new ThreadSafeQueue<Object>(); }
public StatsViewer( APPLICATION_DATA appData) { InitializeComponent(); m_AppData = appData; m_StatGroups = m_AppData.HealthStatistics.GetGroupList(); m_AllStats = m_AppData.HealthStatistics.GetStatList(); m_GroupManager = new STAT_GROUP_MANAGER(); m_GroupManager.LoadGroups(m_StatGroups); singleton = new object(); ButtonSize = new Size(this.Size.Width/4, 25 ); Locations = new Point[NUM_BUTTONS]; m_PushStatusInfoQ = new ThreadSafeQueue<string>(2); m_ButtonClickHandlers = new ButtonClick[NUM_BUTTONS]; // row one Locations[0] = new Point(0, 0); Locations[1] = new Point(ButtonSize.Width, 0); Locations[2] = new Point(ButtonSize.Width*2, 0); Locations[3] = new Point(ButtonSize.Width*3, 0); // row two Locations[4] = new Point(0, ButtonSize.Height); Locations[5] = new Point(ButtonSize.Width, ButtonSize.Height); Locations[6] = new Point(ButtonSize.Width * 2, ButtonSize.Height); Locations[7] = new Point(ButtonSize.Width * 3, ButtonSize.Height); ButtonUsed = new bool[NUM_BUTTONS]; Buttons = new Button[NUM_BUTTONS]; for (int b = 0; b < NUM_BUTTONS; b++) { Buttons[b] = new Button(); ButtonUsed[b] = false; } int groupCnt = 0; foreach (string group in m_StatGroups) { if (groupCnt == NUM_BUTTONS) break; int b = GetNextAvailableButton(); DefineButton(Buttons[b], ButtonSize, group, Locations[b], b); this.Controls.Add(Buttons[b]); } foreach (string group in m_StatGroups) { GridTableManager grid = new GridTableManager(); grid.CreateGrid(new Size(this.Size.Width, this.Size.Height - 50), new Point(0, 50)); m_GroupManager[group].AddGrid(grid); } }
public void GetNextReturnsFalseWhenEmpty() { //Arrange var q = new ThreadSafeQueue<string>(); //Act var res = q.TryGetNext(); //Assert Assert.That(res.IsSuccess); Assert.That(res.Result.Item1 == false); }
/// Constructor for client-side session. public LoopbackSession(IoService service, LoopbackEndPoint localEP, IoHandler handler, LoopbackPipe remoteEntry) : base(service) { Config = new DefaultLoopbackSessionConfig(); _lock = new Byte[0]; _localEP = localEP; _remoteEP = remoteEntry.Endpoint; _filterChain = new LoopbackFilterChain(this); _receivedMessageQueue = new ThreadSafeQueue<Object>(); _remoteSession = new LoopbackSession(this, remoteEntry); }
//[TestMethod] public void ComplexTestSlow() { ThreadSafeQueue <int> q = new ThreadSafeQueue <int>(); Random rnd = new Random(); q.MaxCount = 2003; for (int i = 0; i < 10; i++) { q.MaxCount = rnd.Next(1000, 10000); RunComplexTest(q, int.MaxValue / 200, Math.Max(1, Environment.ProcessorCount / 2) + (i % 4) + rnd.Next(1)); } }
public void It_adds_items_in_the_collection_to_the_queue() { var queue = new ThreadSafeQueue <string>(new List <string> { "1", "2", "3" }); queue.EnqueueRange(new List <string> { "4", "5", "6" }); Assert.That(queue.Count, Is.EqualTo(6)); Assert.That(queue.Contains("6")); }
public void It_copies_items_to_array() { var array = new string[3]; var queue = new ThreadSafeQueue <string>(new List <string> { "1", "2", "3" }); Assert.DoesNotThrow(() => queue.CopyTo(array, 0)); Assert.That(array.Length, Is.EqualTo(3)); Assert.That(array[0], Is.EqualTo("1")); Assert.That(array[1], Is.EqualTo("2")); Assert.That(array[2], Is.EqualTo("3")); }
public void Add_Element_On_Queue_Until_Full_It() { ThreadSafeQueue <int> threadSafeQueue = new ThreadSafeQueue <int>(5); threadSafeQueue.Enqueue(1); threadSafeQueue.Enqueue(2); threadSafeQueue.Enqueue(3); threadSafeQueue.Enqueue(4); threadSafeQueue.Enqueue(5); Assert.False(threadSafeQueue.IsEmpty()); Assert.True(threadSafeQueue.IsFull()); }
public LPREngine(APPLICATION_DATA appData) { try { m_AppData = appData; m_AppData.AddOnClosing(Stop, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_Log = (ErrorLog)m_AppData.Logger; m_FrameGen = (FrameGenerator)m_AppData.FrameGenerator; m_LPRProcessQ = new ThreadSafeQueue<FRAME>(m_LPRProcessQueSize, "QueueOverruns_LPR_LPRProcessQ", m_AppData); // this queue hold frames that come from the framegenerator and need to be processed by LPR m_AppData.LPRGettingBehind = false; m_LPRFinalPlateGroupOutputQ = new ThreadSafeQueue<FRAME>(60, "QueueOverruns_LPR_LPRFinalPlateGroupOutputQ", m_AppData); // filtered plate readings, grouped into similar readings, redundant readings removed m_LPRPerFrameReadingQ = new ThreadSafeQueue<FRAME>(60, "QueueOverruns_LPR_LPRPerFrameReadingQ", m_AppData); // instantaneous output from LPR for each fram processed m_StoredFrameData = new ThreadSafeHashableQueue(30 * 60);// 60 seconds of frames at 30fps m_LPRFuntions = new LPROCR_Lib(); unsafe { // the plate group processor accumulates per-frame plate readings and consolidates them into a single plate reading where appropriate m_LPRFuntions.RegisterPlateGroupCB(OnNewPlateGroupReady); } int maxW = 0, minW = 0, maxH = 0, minH = 0; m_LPRFuntions.GetMinMaxPlateSize(ref minW, ref maxW,ref minH, ref maxH); m_AppData.MAX_PLATE_HEIGHT = maxH; m_AppData.MIN_PLATE_HEIGHT = minH; m_AppData.MAX_PLATE_WIDTH = maxW; m_AppData.MIN_PLATE_WIDTH = minW; m_processOptions = new LPROCR_Lib.LPR_PROCESS_OPTIONS(); m_processOptions.roll = 1; m_processOptions.rotation = 1; // register with the frame grabber to get new bitmaps from the channel sources as they come in m_ConsumerID = m_FrameGen.GetNewConsumerID(); // m_NumSourceChannels = m_FrameGen.GetNumberOfConfiguredChannels(); m_NumSourceChannels = (m_AppData.RunninAsService) ? m_AppData.MAX_PHYSICAL_CHANNELS : m_AppData.MAX_VIRTUAL_CHANNELS; m_LPREngineProcessThread = new Thread(LPREngineProcessLoop); PushLPRResultsThread = new Thread(PushLPRResultsLoop); } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } }
public MovieFiles(APPLICATION_DATA appData) { m_AppData = appData; m_AppData.AddOnClosing(OnClose, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_Log = (ErrorLog)m_AppData.Logger; MovieControlSingleton = new object(); m_ProcessThread = new Thread(ProcessLoop); m_PlayCommandsQ = new ThreadSafeQueue<MOVIE_PLAY_CONTROL_OBJECT>(20); m_NewFramesToPushQ = new ThreadSafeQueue<FRAME>(240); m_PushFramesToCosumersThread = new Thread(PushFramesToConsumersLoop); m_MasterFileList = new ThreadSafeHashTable(1000); vChans = new VIRTUAL_CHANNEL[m_AppData.MAX_VIRTUAL_CHANNELS]; }
public void ShouldEnqueueColletionOfItems() { var expected = new[] { "hello", "world" }; var queue = new ThreadSafeQueue <string>(); queue.Enqueue(expected); var actual = queue.DequeueAll(); Assert.Equal(expected, actual); }
public Process(ThreadSafeQueue <IPausableTask> newTaskRoutines, FasterList <IPausableTask> coroutines, FlushingOperation flushingOperation, RunningTasksInfo info, FlushTasksDel flushTaskDel, RunnerBehaviour runnerBehaviourForUnityCoroutine = null, Action <IPausableTask> resumeOperation = null) { this._newTaskRoutines = newTaskRoutines; this._coroutines = coroutines; this._flushingOperation = flushingOperation; this._info = info; this._flushTaskDel = flushTaskDel; this._runnerBehaviourForUnityCoroutine = runnerBehaviourForUnityCoroutine; this._resumeOperation = resumeOperation; }
private static void DoCunsume(ThreadSafeQueue<int> queue) { while (true) { try { int num = queue.Pop(); Console.WriteLine("Thread {0} consuming value {1}", Thread.CurrentThread.ManagedThreadId, num); } catch { Console.WriteLine("Thread {0} consuming end", Thread.CurrentThread.ManagedThreadId); return; } } }
public MovieFiles(APPLICATION_DATA appData) { m_AppData = appData; m_AppData.AddOnClosing(OnClose, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_Log = (ErrorLog)m_AppData.Logger; MovieControlSingleton = new object(); m_ProcessThread = new Thread(ProcessLoop); m_PlayCommandsQ = new ThreadSafeQueue <MOVIE_PLAY_CONTROL_OBJECT>(20); m_NewFramesToPushQ = new ThreadSafeQueue <FRAME>(240); m_PushFramesToCosumersThread = new Thread(PushFramesToConsumersLoop); m_MasterFileList = new ThreadSafeHashTable(1000); vChans = new VIRTUAL_CHANNEL[m_AppData.MAX_VIRTUAL_CHANNELS]; }
public override void StartServer() { StopServer(); Incoming = new ThreadSafeQueue <byte>(); Outgoing = new ThreadSafeQueue <byte>(); Port.Open(); _isRunning = true; Reader = Task.Run((Action)ReaderProcess); Writer = Task.Run((Action)WriterProcess); Reader.Start(); Writer.Start(); }
public void ShouldDequeueAllAfterAdded() { var expected = new[] { "hello", "world" }; var queue = new ThreadSafeQueue <string>(); queue.Enqueue("hello"); queue.Enqueue("world"); var actual = queue.DequeueAll(); Assert.Equal(expected, actual); }
// ///////////////// // // design // // at startup, count how many external drives are available - there should only be one. // // if one drive, select that drive and create the default storage directory // then inform the DVR function that a drive has been found and is ready // // setup a function to watch for changes in connected drives // if a new drive is added, start the hotswap switch over, expect the previous drive to be disconnected // if the currently selected drive is disconnected, notify the DVR the primary drive was lost // if no drives are available, watch for new ones to be added, if one is added make it the primary. public DriveManager(APPLICATION_DATA appData, OnDriveChangeEvent callback, string defaultStorageDir ) { try { m_AppData = appData; m_AppData.AddOnClosing(Stop, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_Log = (ErrorLog)m_AppData.Logger; OnDriveChange = callback; m_DefaultStorageDirectory = defaultStorageDir; singleton = new object(); m_HotSwapStatusString = new ThreadSafeQueue<string>(20); // make the list of current drives now that we are going into a active mode m_DriveListAtStartup = Environment.GetLogicalDrives();// to be used later if a drive change is detected // are we running as AnalystsWorkstation, and no repositories found? if so, then use user-config storage area instead bool runDriveCheckLoop = true; if ( ! m_AppData.RunninAsService) { string[] drives = GetAllFirstEvidenceDrives(); if ( drives == null) drives = new string[0]; if (drives.Length < 1) { // runDriveCheckLoop = false; m_Log.Log("User App Path = " + Application.UserAppDataPath, ErrorLog.LOG_TYPE.INFORMATIONAL); m_CentralRepositoryDrive = Application.UserAppDataPath.Split(':')[0]+ ":\\"; m_SelectedDrive = m_CentralRepositoryDrive; m_Log.Log("dm setting central to " + m_CentralRepositoryDrive, ErrorLog.LOG_TYPE.INFORMATIONAL); RunDelayedDriveChangeNoticeThread();// run the new drive notify after this constructor completes execution } } // look for drive changes.. // SetupDriveWatcher(); // USB events do not always fire correctly when hubs are used on certain computers if ( runDriveCheckLoop) StartPollForDriveChangesThread(); } catch (Exception ex) { m_Log.Log("DriveManager ex: " + ex.Message, ErrorLog.LOG_TYPE.FATAL); } }
public Process(ThreadSafeQueue <IPausableTask> newTaskRoutines, FasterList <IPausableTask> coroutines, FlushingOperation flushingOperation, RunningTasksInfo info, FlushTasksDel flushTaskDel, RunnerBehaviour runnerBehaviourForUnityCoroutine = null, Action <IPausableTask> resumeOperation = null) { _newTaskRoutines = newTaskRoutines; _coroutines = coroutines; _flushingOperation = flushingOperation; _info = info; _flushTaskDel = flushTaskDel; _runnerBehaviourForUnityCoroutine = runnerBehaviourForUnityCoroutine; _resumeOperation = resumeOperation; _platformProfiler = new Svelto.Common.PlatformProfiler(_info.runnerName); }
public void It_should_not_throw_exception_if_queue_is_modified() { var count = 0; var queue = new ThreadSafeQueue <string>(new List <string> { "1", "2", "3" }); // ReSharper disable once UnusedVariable foreach (var item in queue) { queue.Enqueue($"{count + 4}"); count++; } Assert.That(count, Is.EqualTo(3)); Assert.That(queue.Count, Is.EqualTo(6)); }
private SemaphoreSlim(int initialCount, int?maxCount) { if (initialCount < 0 || initialCount > maxCount) { throw new ArgumentOutOfRangeException(nameof(initialCount), "initialCount < 0 || initialCount > maxCount"); } if (maxCount <= 0) { throw new ArgumentOutOfRangeException(nameof(initialCount), "maxCount <= 0"); } _maxCount = maxCount; _asyncWaiters = new ThreadSafeQueue <TaskCompletionSource <bool> >(); _count = initialCount; _canEnter = new ManualResetEventSlim(_count > 0); }
public void StartRegistration() { m_LPREngine = (LPREngine)m_AppData.LPREngine; for (int c = 0; c < m_NumberChannels; c++) { try { m_CurrentImageQ[c] = new ThreadSafeQueue <FRAME>(3); m_FrameGenerator.RegisterToConsumeChannel(m_ConsumerID, c, (FrameGenerator.NotificationOfNewFrameReady)NewImageCallBack); m_CurrentPlateNumberQ[c] = new ThreadSafeQueue <FRAME>(3); m_LPREngine.OnNewUnfilteredPlateEvent += new LPREngine.NewPlateEvent(m_LPREngine_OnNewPlateEvent); // get unfiltered plate readings for user display } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } } }
public WorkerManager() { jobDistributor = new Thread(JobDistributor); jobsToDo = new ThreadSafeQueue <int>(); for (int i = 0; i < jobsForWorkers.Length; i++) { jobsForWorkers[i] = new Job(); } int numWorkers = Math.Max(1, ThreadedJobs.AVAILABLE_CORES); workers = new Worker[numWorkers]; for (int i = 0; i < workers.Length; i++) { workers[i] = new Worker(this, i); } jobDistributor.Name = "Job distributor"; jobDistributor.Start(); }
public RunnerData(bool relaxed, float interval, string name, bool isRunningTightTasks) { _mevent = new ManualResetEventEx(); _watch = new Stopwatch(); _coroutines = new FasterList <ISveltoTask <T> >(); newTaskRoutines = new ThreadSafeQueue <ISveltoTask <T> >(); _intervalInTicks = (long)(interval * Stopwatch.Frequency / 1000); this.name = name; _isRunningTightTasks = isRunningTightTasks; if (relaxed) { _lockingMechanism = RelaxedLockingMechanism; } else { _lockingMechanism = QuickLockingMechanism; } }
public override void StartServer() { StopServer(); Incoming = new ThreadSafeQueue <byte>(); Outgoing = new ThreadSafeQueue <byte>(); Reader = new Thread(ReaderProcess); Reader.IsBackground = true; Writer = new Thread(WriterProcess); Writer.IsBackground = true; Port.Open(); _isRunning = true; Reader.Start(); Writer.Start(); }
public override void StartServer() { StopServer(); Incoming = new ThreadSafeQueue<byte>(); Outgoing = new ThreadSafeQueue<byte>(); Reader = new Thread(ReaderProcess); Reader.IsBackground = true; Writer = new Thread(WriterProcess); Writer.IsBackground = true; Port.Open(); _isRunning = true; Reader.Start(); Writer.Start(); }
public RunnerData(bool relaxed, float interval, string name, bool isRunningTightTasks) { _mevent = new ManualResetEventEx(); _watch = new Stopwatch(); _coroutines = new FasterList <IPausableTask>(); _newTaskRoutines = new ThreadSafeQueue <IPausableTask>(); _interval = (long)(interval * 10000); _name = name; _isRunningTightTasks = isRunningTightTasks; if (relaxed) { LockingMechanism = RelaxedLockingMechanism; } else { LockingMechanism = QuickLockingMechanism; } }
private static IPromise <T> AddExecution <T>(Func <T> action, ThreadSafeQueue <Action> queue) { var promised = new PromiseNeedle <T>(false); var result = new ReadOnlyPromiseNeedle <T>(promised); queue.Add ( () => { try { promised.Value = action.Invoke(); } catch (Exception exception) { promised.SetError(exception); } }); return(result); }
public void StartRegistration() { m_LPREngine = (LPREngine)m_AppData.LPREngine; for (int c = 0; c < m_NumberChannels; c++) { try { m_CurrentImageQ[c] = new ThreadSafeQueue<FRAME>(3); m_FrameGenerator.RegisterToConsumeChannel(m_ConsumerID, c, (FrameGenerator.NotificationOfNewFrameReady)NewImageCallBack); m_CurrentPlateNumberQ[c] = new ThreadSafeQueue<FRAME>(3); m_LPREngine.OnNewUnfilteredPlateEvent += new LPREngine.NewPlateEvent(m_LPREngine_OnNewPlateEvent); // get unfiltered plate readings for user display } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } } }
private static IPromise AddExecution(Action action, ThreadSafeQueue <Action> queue) { var promised = new Promise(false); var result = new ReadOnlyPromise(promised); queue.Add ( () => { try { action.Invoke(); promised.SetCompleted(); } catch (Exception exception) { promised.SetError(exception); } }); return(result); }
/// <summary> /// Create a dynamic sound effect instance with the given sound properties. /// </summary> /// <param name="engine">The engine in which the dynamicSoundEffectInstance is created</param> /// <param name="sampleRate">Sample rate, in Hertz (Hz), of audio content. Must between 8000 Hz and 48000 Hz</param> /// <param name="channels">Number of channels in the audio data.</param> /// <param name="encoding">Encoding of a sound data sample</param> /// <returns>A new DynamicSoundEffectInstance instance ready to filled with data and then played</returns> /// <exception cref="ArgumentOutOfRangeException">This exception is thrown for one of the following reason: /// <list type="bullet"> /// <item>The value specified for sampleRate is less than 8000 Hz or greater than 48000 Hz. </item> /// <item>The value specified for channels is something other than mono or stereo. </item> /// <item>The value specified for data encoding is something other than 8 or 16 bits. </item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"><paramref name="engine"/> is null.</exception> public DynamicSoundEffectInstance(AudioEngine engine, int sampleRate, AudioChannels channels, AudioDataEncoding encoding) : base(engine) { if (engine == null) throw new ArgumentNullException("engine"); if (sampleRate < 8000 || 48000 < sampleRate) throw new ArgumentOutOfRangeException("sampleRate"); if(channels != AudioChannels.Mono && channels != AudioChannels.Stereo) throw new ArgumentOutOfRangeException("channels"); if(encoding != AudioDataEncoding.PCM_8Bits && encoding != AudioDataEncoding.PCM_16Bits) throw new ArgumentOutOfRangeException("encoding"); waveFormat = new WaveFormat(sampleRate, (int)encoding, (int)channels); Interlocked.Increment(ref totalNbOfInstances); Interlocked.Increment(ref numberOfInstances); // first instance of dynamic sound effect instance => we create the workerThead and the associated event. if (numberOfInstances == 1) { instancesNeedingBuffer = new ThreadSafeQueue<DynamicSoundEffectInstance>(); // to be sure that there is no remaining request from previous sessions awakeWorkerThread = new AutoResetEvent(false); CreateWorkerThread(); } Name = "Dynamic Sound Effect Instance - "+totalNbOfInstances; CreateVoice(WaveFormat); InitializeDynamicSound(); AudioEngine.RegisterSound(this); ResetStateToDefault(); }
public RemoteConnectionServer( APPLICATION_DATA appData ) { try { m_AppData = appData; m_AppData.AddOnClosing(OnClose, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_Log = (ErrorLog)m_AppData.Logger; m_FrameLock = new object(); m_FrameGenerator = (FrameGenerator)m_AppData.FrameGenerator; m_NumberChannels = m_FrameGenerator.GetNumberOfPhysicalChannels(); m_ConsumerID = m_FrameGenerator.GetNewConsumerID(); m_CurrentImageQ = new ThreadSafeQueue<FRAME>[m_NumberChannels]; m_CurrentPlateNumberQ = new ThreadSafeQueue<FRAME>[m_NumberChannels]; m_Log = (ErrorLog)m_AppData.Logger; m_LocalHostPortsTable = new ThreadSafeHashTable(5); m_Server = new List<ConnectionServer>(); } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } }
private static void DoProduce(ThreadSafeQueue<int> queue) { Random rand = new Random(); try { for (int i = 0; i < MaxNumProducing; i++) { int value = rand.Next(MaxRandom); Console.WriteLine("Thread {0} producing value {1}", Thread.CurrentThread.ManagedThreadId, value); queue.Push(value); } queue.Close(); Console.WriteLine("Thread {0} producing end", Thread.CurrentThread.ManagedThreadId); } catch { Console.WriteLine("Thread {0} producing interrupted", Thread.CurrentThread.ManagedThreadId); } }
void RunMultiThreadParallelTasks() { if (_maxConcurrentTasks == uint.MaxValue) _maxConcurrentTasks = (uint)(registeredEnumerators.Count); else _maxConcurrentTasks = Math.Min(_maxConcurrentTasks, (uint)(registeredEnumerators.Count)); _maxConcurrentTasks = Math.Min(MAX_CONCURRENT_TASK, _maxConcurrentTasks); _registeredEnumerators = new ThreadSafeQueue<IEnumerator>(registeredEnumerators); for (int i = 0; i < _maxConcurrentTasks; i++) if (_registeredEnumerators.Count > 0) RunNewParallelTask(); }
public void ShouldCreateNewInstance() { var queue = new ThreadSafeQueue <string>(); Assert.NotNull(queue); }
public AnalystsWorkstationMainForm() { InitializeComponent(); m_LPRCore = new LPRServiceEntryPoint(); m_AppData = m_LPRCore.GetAppData(); this.Text = "First Evidence Plate Analysts Workstation, version " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); /// /// enable LPR Diagnostics /// if (Application.ExecutablePath.Contains("Visual Studio")) // assumes I am debugging on Vista { m_AppData.LPRDiagEnabled = true; } else { m_AppData.LPRDiagEnabled = false; } m_AppData.LPRDiagEnabled = false; // Remove Diagnostic tabs if not in diag mode if (!m_AppData.LPRDiagEnabled) { tabControlMain.TabPages.Remove(tabPageLPRDiagnostics); tabControlMain.TabPages.Remove(tabPageOCRLib); } else { OCRSourceFolder = UserSettings.Get(UserSettingTags.AW_OCRLibSourceDirectory); labelOCRSourceFolder.Text = OCRSourceFolder; OCRDestinationFolder = UserSettings.Get(UserSettingTags.AW_OCRLibDestinationDirectory); labelOCRDestinationFolder.Text = OCRDestinationFolder; } //// need some channel names assigned as place holders, off-line processing simulates hardware channels to the rest of the chain //for (int i = 0; i < m_AppData.MAX_VIRTUAL_CHANNELS; i++) // UserSettings.Set(UserSettingTags.ChannelNames.Name(i), i.ToString()); // allow parallel processing based on the number of cores. The ProcessorCount returns the number of cores m_AppData.MAX_VIRTUAL_CHANNELS = Math.Min(Environment.ProcessorCount,m_AppData.MAX_PHYSICAL_CHANNELS); m_DataGridRowIndex = new ThreadSafeHashTable(m_AppData.MAX_MOVIE_FILES_TO_LOAD); m_AppData.MoviePlayerParentForm = (object)this; m_AppData.RunninAsService = false; m_LPRCore.Start(m_AppData.RunninAsService); m_LPREngine = (LPREngine)m_AppData.LPREngine; m_LPREngine.OnNewFilteredPlateGroupEvent += new LPREngine.NewPlateEvent(m_LPREngine_OnNewPlateEvent); m_Log = (ErrorLog)m_AppData.Logger; m_FrameGenerator = (FrameGenerator)m_AppData.FrameGenerator; this.FormClosing += new FormClosingEventHandler(AnalystsWorkstationMainForm_FormClosing); m_PathManager = (PATHS)m_AppData.PathManager; m_DVR = (DVR)m_AppData.DVR; m_SmartSearchUC = new SmartSearchLibUC(m_AppData, OnSearchFatalError); m_SmartSearchUC.Location = new Point(0, 0); m_SmartSearchUC.Dock = DockStyle.Fill; CreateBatchModeVideoDisplayPanels(); m_FrameGenerator.MovieFileController.DisplayPanels = m_VideoDisplayPanels; m_FrameGenerator.MovieFileController.OnStatusUpdateFromPlayerEvent += new MovieFiles.OnStatusUpdateFromPlayer(MovieFileController_OnStatusUpdateFromPlayerEvent); tabPageSearch.Controls.Add(m_SmartSearchUC); InitMainContainerGrid(dataGridViewFilesInProcess, new System.Drawing.Size(761, 200), new System.Drawing.Point(273, 483)); m_EditModePictureSelectionViewer = new ListView(); m_EditModePictureSelectionViewer.Location = new Point(219, 200); m_EditModePictureSelectionViewer.View = View.LargeIcon; m_EditModePictureSelectionViewer.Size = new Size(this.Size.Width - 275, this.Size.Height - 300); m_EditModePictureSelectionViewer.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(m_EditModePictureSelectionViewer_ItemSelectionChanged); buttonListViewVisible.Text = m_ShowThumbNails; m_EditModePictureSelectionViewer.Enabled = false; m_EditModePictureSelectionViewer.Visible = false; m_EditModePictureSelectionViewer.SendToBack(); tabPageEditMode.Controls.Add(m_EditModePictureSelectionViewer); tabControlLPRResults.TabPages.Clear(); // get DVR storage mode for the batch and edit mode processing string sm = UserSettings.Get(UserSettingTags.DVR_StorageMode); if (sm != null) { if (sm.Contains(UserSettingTags.DVR_StorageModeValueStoreOnMotion)) { m_AppData.DVRMode = APPLICATION_DATA.DVR_MODE.STORE_ON_MOTION; radioButtonStoreOnMotion.Checked = true; radioButtonStoreOnPlate.Checked = false; } else { radioButtonStoreOnMotion.Checked = false; radioButtonStoreOnPlate.Checked = true; m_AppData.DVRMode = APPLICATION_DATA.DVR_MODE.STORE_ON_PLATE_FOUND; } } else { radioButtonStoreOnMotion.Checked = false; radioButtonStoreOnPlate.Checked = true; m_AppData.DVRMode = APPLICATION_DATA.DVR_MODE.STORE_ON_PLATE_FOUND; } // by default, store batch outputs to repository radioToRepository.Checked = true; radioButtonToUserSpecifiedStorage.Checked = false; m_AppData.DVR_StoreToUserSpecifiedFolder = false; // now see if the user has previously chosen to store to specific folder -- get the user specified (if present) storage path for batch and edit mode processing string p = UserSettings.Get(UserSettingTags.DVR_UserSpecifiedStoragePath); if (p != null) { if (p.Contains(UserSettingTags.BOOL_TRUE)) { // the user want the batch processing results to go to a special folder and not the repository radioToRepository.Checked = false; string s = UserSettings.Get(UserSettingTags.DVR_UserSpecifiedStoragePath); if (s == null) { // error condition, the config setting says use userspecfifiedstorage, but the path is not there UserSettings.Set(UserSettingTags.DVR_StoreToUserSpecifiedFolder, UserSettingTags.BOOL_FALSE); radioButtonToUserSpecifiedStorage.Checked = false; string drive = null; if (m_PathManager.Drive == null) drive = "No repository found"; else drive = m_PathManager.Drive; textBoxUserSpecifiedStorageLocation.Text = drive; } else { // the good condition, all as it should be m_AppData.DVR_UserSpecifiedStoragePath = s; textBoxUserSpecifiedStorageLocation.Text = s; } } else { // the auto condition, use the DVRSTORAGE default storage area to put images and results into radioButtonToUserSpecifiedStorage.Checked = false; string drive = null; if (m_PathManager.Drive == null) { // if the user has configured a standard repository, then create one in the default user data folder string dirPath = Application.UserAppDataPath + "\\DVRSTORAGE"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(Application.UserAppDataPath + "\\DVRSTORAGE"); } drive = m_PathManager.Drive; } else { drive = m_PathManager.Drive; } textBoxUserSpecifiedStorageLocation.Text = drive; } } // display to the user the time stamps from the processed images so that user has a clue where to find // this images when searching in the search tool { int consumerID = ((FrameGenerator)m_AppData.FrameGenerator).GetNewConsumerID(); int maxChannels = ((FrameGenerator)m_AppData.FrameGenerator).GetNumberOfPhysicalChannels(); for (int c = 0; c < maxChannels; c++) ((FrameGenerator)m_AppData.FrameGenerator).RegisterToConsumeChannel(consumerID, c, OnReceiveNewFrameToExtractTimeStamp); // get callback on new frames m_ToDisplayProcessedTimeStampsQ = new ThreadSafeQueue<FRAME>(240); // store the frames into a Q when calledback. m_DisplayBatchTimeStampsThread = new Thread(DisplayBatchTimeStampsLoop); // empty the Q with this thread, dump to the listbox for user display m_DisplayBatchTimeStampsThread.Start(); } // install the user control to allow the user to import images from a field drive m_ImportImageDrive = new ImportImageDrive(m_AppData); tabPageImportImages.Controls.Add(m_ImportImageDrive); // show the results of LPR strings to the user m_LPRResultsToPostQ = new ThreadSafeQueue<LPR_RESULT_TO_POST>(100); m_LPRPostResultsThread = new Thread(LPRPostResultsLoop); m_LPRPostResultsThread.Start(); // keep tabs on the repository - find one and keep checking for lost drives m_CheckRepositoryStatusThread = new Thread(CheckRepositoryLoop); m_CheckRepositoryStatusThread.Start(); // m_LPRCore.OnSelfDestruct += CloseThis; }
public SEND_PACKET_REQUESTS() { // m_SendPacketRequests = new Queue<RCS_Protocol.RCS_Protocol.PACKET_TYPES>(); m_SendPacketRequests = new ThreadSafeQueue<byte[]>(30); }
public ConcurrentBag() { _wrapped = new ThreadSafeQueue <T>(); }
// constructor public DVR(APPLICATION_DATA appData) { try { m_AppData = appData; m_AppData.AddOnClosing(Stop, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_Log = (ErrorLog)m_AppData.Logger; PauseFlag = new PAUSE_FLAG(); PauseFlag.Pause = true; FileAccessControl = new FILE_SYSTEM_ACCESS(PauseFlag, m_AppData); try { Paths = new PATHS(m_AppData.ThisComputerName, true, m_AppData); m_AppData.PathManager = (object)Paths; } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } m_EventLogFile = new EventLogFiles.EventLogFiles(m_AppData); // PRE MOTION BUFFER LENGHT m_NumberOfFramesToPrePostBuffer = 30; // this many frames before and after moton event, if too small, files may be erased before motion is detected because of processing lag //////// m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.DVR.DVR_DriveName].StatString.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.DVR.DVR_DriveReady].boolean.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.DVR.DVR_FreeSpace].SnapshotDouble.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.DVR.DVR_UsedSpace].SnapshotDouble.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.DVR.DVR_DriveHotSwap].StatString.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.System.System_Drive].StatString.SetValue = "No drive "; m_FrameGenerator = (FrameGenerator)m_AppData.FrameGenerator; m_DriveManager = new DriveManager(m_AppData, OnExternalDriveChange, Paths.StorageDir); // alway use external storage if ( m_AppData.RunninAsService) { int count = 0; Paths.Drive = m_DriveManager.GetDrive(ref count); PauseFlag.DriveExists = true; if (count > 1) { PauseFlag.Pause = true; m_Log.Log("Too many external drives on start", ErrorLog.LOG_TYPE.FATAL); //m_MessageBoxMessage = "Too many external drives on start. Please connect only one external drive and re-start the LPR Service."; //RunMessageBoxDialog(); } else if (Paths.Drive == null) { PauseFlag.Pause = true; m_Log.Log("External Drive not found", ErrorLog.LOG_TYPE.FATAL); // m_MessageBoxMessage = "External drive not found. Please connect one external drive"; PauseFlag.DriveExists = false; // RunMessageBoxDialog(); } } m_ConsumerID = m_FrameGenerator.GetNewConsumerID(); m_NewFrameQ = new ThreadSafeQueue<FRAME>(240, "QueueOverruns_DVR_NewFrameQ", m_AppData); m_MotionDetectedQ = new ThreadSafeQueue<FRAME>(240, "QueueOverruns_DVR_MotionDetectedQ", m_AppData); m_DirectyToStorageQ = new ThreadSafeQueue<FRAME>(240, "QueueOverruns_DVR_DirectyToStorageQ", m_AppData); m_NewLPRRecordQ = new ThreadSafeQueue<FRAME>(m_LPRRecordQueLen, "QueueOverruns_DVR_NewLPRRecordQ", m_AppData); m_TempFileList = new ThreadSafeList<TEMPFILES>(120); m_NumSourceChannels = (m_AppData.RunninAsService) ? m_AppData.MAX_PHYSICAL_CHANNELS : m_AppData.MAX_VIRTUAL_CHANNELS; m_PreMotionRecords = new PRE_MOTION_RECORDS[m_NumSourceChannels]; m_DVRLoopThread = new Thread(DVRLoop); m_ReportDVRStats = new Thread(ReportDVRStatusLoop); m_TempFileCleanUpThread = new Thread(TempFilesCleanUpLoop); m_MaintainFileSystemSizeLimit = new Thread(MaintainFileSystemSizeLimitLoop); } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } }
private void RunComplexTest(ThreadSafeQueue <int> q, int elemCount, int thCount) { int atomicRandom = 0; int trackElemCount = elemCount; int addFinished = 0; Thread[] threadsTake = new Thread[thCount]; Thread[] threadsAdd = new Thread[thCount]; CancellationTokenSource tokSrc = new CancellationTokenSource(); List <int> global = new List <int>(elemCount); Action addAction = () => { Random rnd = new Random(Environment.TickCount + Interlocked.Increment(ref atomicRandom) * thCount * 2); while (true) { int item = Interlocked.Decrement(ref trackElemCount); if (item < 0) { break; } q.TryAdd(item, -1, default(CancellationToken)); int sleepTime = rnd.Next(100); if (sleepTime > 0) { Thread.SpinWait(sleepTime); } } Interlocked.Increment(ref addFinished); }; Action takeAction = () => { Random rnd = new Random(Environment.TickCount + Interlocked.Increment(ref atomicRandom) * thCount * 2); List <int> data = new List <int>(); try { while (Volatile.Read(ref addFinished) < thCount) { int tmp = 0; if (q.TryTake(out tmp, -1, tokSrc.Token)) { data.Add((int)tmp); } int sleepTime = rnd.Next(100); if (sleepTime > 0) { Thread.SpinWait(sleepTime); } } } catch (OperationCanceledException) { } int tmp2; while (q.TryTake(out tmp2, 0, default(CancellationToken))) { data.Add((int)tmp2); } lock (global) global.AddRange(data); }; for (int i = 0; i < threadsTake.Length; i++) { threadsTake[i] = new Thread(new ThreadStart(takeAction)); } for (int i = 0; i < threadsAdd.Length; i++) { threadsAdd[i] = new Thread(new ThreadStart(addAction)); } for (int i = 0; i < threadsTake.Length; i++) { threadsTake[i].Start(); } for (int i = 0; i < threadsAdd.Length; i++) { threadsAdd[i].Start(); } for (int i = 0; i < threadsAdd.Length; i++) { threadsAdd[i].Join(); } tokSrc.Cancel(); for (int i = 0; i < threadsTake.Length; i++) { threadsTake[i].Join(); } Assert.AreEqual(elemCount, global.Count); global.Sort(); for (int i = 0; i < elemCount; i++) { Assert.AreEqual(i, global[i]); } }
/// <summary> /// Starts up the scheduling engine /// </summary> public void StartSchedulingEngine() { for (int n = 0; n < _allWorkItemQueues.Length; n++) { _allWorkItemQueues[n] = new ThreadSafeQueue<IExecutableWorkItem>(); _workItemQueueHandlers[n] = new WorkItemQueueHandler(this, n); _workItemQueueHandlers[n].StartEventHandler(); } }
private void Initialize() { _allWorkItemQueues = new ThreadSafeQueue<IExecutableWorkItem>[TotalThreads]; _workItemQueueHandlers = new WorkItemQueueHandler[TotalThreads]; _currentDateTime = DateTime.Now; }
// inputs // // jpegs from hardware devices // bitmaps from hardware devices // GPS from stored data or hardware devices // Camera name source info from stored configuration // video files on disk // still images on disk // outputs // // bitmaps to LPR, with source, time and GPS // jpegs to DVR, with source, time and GPS // // // // public FrameGenerator(APPLICATION_DATA appData, bool AsService) { try { m_AppData = appData; m_AppData.AddOnClosing(OnClose, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_Log = (ErrorLog)m_AppData.Logger; m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_FrameCnt].Peak.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_FrameCnt].PerSecond.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_FrameCnt].RunningAverage.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_FrameCnt].Snapshot.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_MotionDetectionPendingQ].Peak.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_MotionDetectionPendingQ].PerSecond.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_MotionDetectionPendingQ].RunningAverage.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_MotionDetectionPendingQ].Snapshot.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_NonMotionFramePushQ].Peak.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_NonMotionFramePushQ].PerSecond.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_NonMotionFramePushQ].RunningAverage.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_NonMotionFramePushQ].Snapshot.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.FRAME_GENERATOR.FrameGen_GPSLocation].StatString.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.MOTION_DETECTION.MotionDetector_DroppedFrames].Accumulator.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.MOTION_DETECTION.MotionDetector_FrameCnt].Accumulator.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.MOTION_DETECTION.MotionDetector_FramesDetected].Accumulator.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.MOTION_DETECTION.MotionDetector_ProcessQCnt].Snapshot.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.MOTION_DETECTION.MotionDetector_ProcessQCnt].Peak.RegisterForUse(true); m_EabledChannelArray = new bool[m_AppData.MAX_PHYSICAL_CHANNELS];// used tell the 2255 device which of its channels are enabled m_LastJPEGReceived = new LAST_JPEG_RECEIVED[m_AppData.MAX_PHYSICAL_CHANNELS]; m_Channels = new CHANNEL[m_AppData.MAX_PHYSICAL_CHANNELS]; for (int c = 0; c < m_AppData.MAX_PHYSICAL_CHANNELS; c++) { m_LastJPEGReceived[c] = new LAST_JPEG_RECEIVED(); m_Channels[c] = new CHANNEL(c); } LoadChannelNames(); m_ConsumerIDs = new CONSUMER_ID(); m_CurrentGPSPosition = m_NoPositionAvailable; m_MotionDetectionQ = new ThreadSafeQueue <FRAME>(m_MotionDetectionQueLevel, "QueueOverruns_FG_MotionDetectionQ", m_AppData); m_AppData.MotionDetectionGettingBehind = false; ////////////////////////////////////// // // start the thread that pushes new frames to the registered consumers m_AllFramesConsumerPushQ = new ThreadSafeQueue <CONSUMER_PUSH>(240, "QueueOverruns_FG_AllFramesConsumerPushQ", m_AppData); m_MotionDetectedConsumerPushQ = new ThreadSafeQueue <CONSUMER_PUSH>(240, "QueueOverruns_FG_MotionDetectedConsumerPushQ", m_AppData); //120 PushThread = new Thread(PushLoop); PushThread.Priority = ThreadPriority.AboveNormal; PushThread.Start(); m_MotionDetectionThread = new Thread(MotionDetectionLoop); m_MotionDetectionThread.Start(); ////////////////////////////////////// // // start the S2255 controller // the 2255 controller has a polling loop that looks for 2255 devices to be added/deleted by the user plugging/unplugging the cables // as new devices are detected, the stored config data is read and the channels are assigned and start running as appropriate // the image data flows into this class via callbacks. this class then pushes the data up a layer after adding GPS and time stamps. if (AsService) { try { S2255Controller.S2255Controller.PAL_NTSC_MODE videoStandard = S2255Controller.S2255Controller.PAL_NTSC_MODE.NTSC; string NTSC_PAL = UserSettings.Get(UserSettingTags.VideoSetup_PAL_NTSC); if (NTSC_PAL != null) { if (NTSC_PAL.Equals(UserSettingTags.VideoSetup_PAL)) { videoStandard = S2255Controller.S2255Controller.PAL_NTSC_MODE.PAL; } } unsafe { m_S2255Controller = new S2255Controller.S2255Controller(videoStandard, m_AppData, m_EabledChannelArray); m_S2255Controller.OnNewFrame += new S2255Controller.S2255Controller.OnNewFrameFromDeviceEvent(OnReceiveNewImageFromS2255Device); m_S2255Controller.StartThreads(); } } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } ////////////////////////////////////// // // start the GPS Controller string GPSPort = FindDevicePort.GetGPSCommPort(); m_GPSController = new GPSController(PutNewGPSData, m_AppData); if (m_S2255Controller.GetReadyStatus) { m_FrameGenReadyStatus = true; } else { m_FrameGenReadyStatus = false; } } if (!AsService) { MovieFileController = new MovieFiles(m_AppData); MovieFileController.OnNewImage += new MovieFiles.OnNewImageEvent(MovieFiles_OnNewImage); MovieFileController.Start(); } } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } }
private ServiceState() { AllLogs = new ThreadSafeList<RotatedLog>(); LastKnownLogHashes = new ThreadSafeDictionary<string, string>(); HashesOfPendingLogs = new ThreadSafeQueue<string>(); }
// Capacity: Number of requests to queue before denying additional ones. public RequestProcessingManager(RequestCallback callback, int capacity) { this.m_capacity = capacity; this.m_callback = callback; m_requestQueue = new ThreadSafeQueue<IRequestObject>(); m_pool = new Semaphore(0, m_capacity); m_continueWork = new ManualResetEvent(false); StartDequeueThread(); }
public SEND_PACKET_REQUESTS() { // m_SendPacketRequests = new Queue<RCS_Protocol.RCS_Protocol.PACKET_TYPES>(); m_SendPacketRequests = new ThreadSafeQueue <byte[]>(30); }
protected BaseRunner(string name) { _name = name; _newTaskRoutines = new ThreadSafeQueue <T>(NUMBER_OF_INITIAL_COROUTINE); _coroutines = new FasterList <T>(NUMBER_OF_INITIAL_COROUTINE); }
private SocketEngine() { curConnectType = isConnectType.isDisconnect; workQueue = new ThreadSafeQueue <SocketTask>(QUEUE_CAPACITY); TaskQueue = new Dictionary <int, SocketTask>(); }
private void start() { accepting = true; disposing = false; closing = false; notifications = new ThreadSafeQueue<Notification>(); Id = System.Guid.NewGuid().ToString("N"); ReconnectDelay = 3000; //3 seconds SendRetries = 3; apnsChannel.ReconnectDelay = this.ReconnectDelay; apnsChannel.ConnectRetries = SendRetries * 2; apnsChannel.Error += new NotificationChannel.OnError(OnChannelError); apnsChannel.Connected += new NotificationChannel.OnConnected(OnChannelConnected); apnsChannel.Connecting += new NotificationChannel.OnConnecting(OnChannelConnecting); apnsChannel.Disconnected += new NotificationChannel.OnDisconnected(OnChannelDisconnected); workerThread = new Thread(new ThreadStart(workerMethod)); workerThread.Start(); }
public static Progressor <T> CreateFromIObservable(IObservable <T> observable, Action exhaustedCallback = null, CancellationToken token = default) { if (observable == null) { throw new ArgumentNullException(nameof(observable)); } if (exhaustedCallback == null) { exhaustedCallback = ActionHelper.GetNoopAction(); } var buffer = new ThreadSafeQueue <T>(); var semaphore = new SemaphoreSlim(0); var source = new CancellationTokenSource(); var subscription = observable.Subscribe ( new CustomObserver <T> ( source.Cancel, _ => source.Cancel(), OnNext ) ); var proxy = new ProxyObservable <T>(); var tryTake = new TryTake <T>[] { null }; tryTake[0] = TakeInitial; void OnNext(T item) { buffer.Add(item); semaphore.Release(); } bool TakeInitial(out T value) { if (source.IsCancellationRequested || token.IsCancellationRequested) { if (Interlocked.CompareExchange(ref tryTake[0], TakeReplacement, tryTake[0]) == tryTake[0]) { Interlocked.Exchange(ref subscription, null)?.Dispose(); semaphore.Dispose(); source.Dispose(); } } else { if (exhaustedCallback != null) { var spinWait = new SpinWait(); while ( semaphore.CurrentCount == 0 && !source.IsCancellationRequested && !token.IsCancellationRequested ) { exhaustedCallback(); spinWait.SpinOnce(); } } } if (source.IsCancellationRequested || token.IsCancellationRequested) { return(TakeReplacement(out value)); } try { semaphore.Wait(source.Token); } catch (OperationCanceledException exception) { No.Op(exception); } return(TakeReplacement(out value)); } bool TakeReplacement(out T value) { if (buffer.TryTake(out value)) { return(true); } value = default; return(false); } bool Take(out T value) { return(tryTake[0](out value)); } return(new Progressor <T>(proxy, Take)); }
public void Clear() { _wrapped = new ThreadSafeQueue <T>(); }
public V2LoadingThread(V2Cache cache) { loadingQueue = new ThreadSafeQueue <Node>(); this.cache = cache; }
protected BaseRunner(string name, int size) { _name = name; _newTaskRoutines = new ThreadSafeQueue <T>(size); _coroutines = new FasterList <T>(size); }