public Tuple<Dictionary<int, int>, Dictionary<string, int>, Dictionary<int, JObject>> createPersonsLots(Dictionary<string, Dictionary<string, NomValue>> noms) { Stopwatch timer = new Stopwatch(); timer.Start(); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; ConcurrentQueue<int> personIds = new ConcurrentQueue<int>(this.getPersonIds()); ConcurrentDictionary<int, int> personIdToLotId = new ConcurrentDictionary<int, int>(); ConcurrentDictionary<string, int> personEgnToLotId = new ConcurrentDictionary<string, int>(); ConcurrentDictionary<int, JObject> personLotIdToPersonNom = new ConcurrentDictionary<int, JObject>(); Utils.RunParallel("ParallelMigrations", ct, () => this.personLotCreatorFactory().Value, (personLotCreator) => { using (personLotCreator) { personLotCreator.StartCreating(noms, personIds, personIdToLotId, personEgnToLotId, personLotIdToPersonNom, cts, ct); } }) .Wait(); timer.Stop(); Console.WriteLine("Person lot creation time - {0}", timer.Elapsed.TotalMinutes); return Tuple.Create( personIdToLotId.ToDictionary(kvp => kvp.Key, kvp => kvp.Value), personEgnToLotId.ToDictionary(kvp => kvp.Key, kvp => kvp.Value), personLotIdToPersonNom.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)); }
public EventMailBox(string aggregateRootId, int batchSize, Action<IList<EventCommittingContext>> handleMessageAction) { _aggregateRootId = aggregateRootId; _messageQueue = new ConcurrentQueue<EventCommittingContext>(); _batchSize = batchSize; _handleMessageAction = handleMessageAction; }
public TestResultHandler(Action<Packet> packetHandler = null) { _packetHandler = packetHandler ?? (packet => { }); Messages = new ConcurrentQueue<Packet>(); Task.Run(() => { try { IsActive = true; while (!_cancellationTokenSource.IsCancellationRequested) { Packet packet; if (Messages.TryDequeue(out packet)) { _packetHandler(packet); } Thread.Sleep(1); } } finally { IsActive = false; } }); }
/// <summary> /// Initializes a new instance of the <see cref="ZyGames.Framework.RPC.Sockets.ExSocket"/> class. /// </summary> /// <param name="socket">Socket.</param> public ExSocket(Socket socket) { HashCode = Guid.NewGuid(); sendQueue = new ConcurrentQueue<SocketAsyncResult>(); this.socket = socket; InitData(); }
public LogTextWriter(string filePath, string prefix = null, string suffix = null, string newline = "\n") { _outputQueue = new ConcurrentQueue<string>(); _outputRun = 1; _outputThread = new Thread(() => { string o; using (FileStream _fs = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read)) { _innerWriter = new StreamWriter(_fs); _innerWriter.NewLine = newline; while (Thread.VolatileRead(ref _outputRun) == 1 || _outputQueue.Count > 0) { if (_outputQueue.Count > 0) { while (_outputQueue.TryDequeue(out o)) _innerWriter.Write(o); _innerWriter.Flush(); } else Thread.Sleep(_outputThreadDelay); } // _fs.Close(); _innerWriter.Close(); } }); _outputThread.Priority = ThreadPriority.BelowNormal; _outputThread.Start(); _prefix = prefix; _suffix = suffix; }
/******************************************************** * PUBLIC CONSTRUCTOR *********************************************************/ /// <summary> /// Console result handler constructor. /// </summary> /// <remarks>Setup the default sampling and notification periods based on the backtest length.</remarks> public ConsoleResultHandler(AlgorithmNodePacket packet) { FinalStatistics = new Dictionary<string, string>(); Log.Trace("Launching Console Result Handler: QuantConnect v2.0"); Messages = new ConcurrentQueue<Packet>(); Charts = new ConcurrentDictionary<string, Chart>(); _chartLock = new Object(); _isActive = true; // we expect one of two types here, the backtest node packet or the live node packet if (packet is BacktestNodePacket) { var backtest = packet as BacktestNodePacket; _algorithmNode = new BacktestConsoleStatusHandler(backtest); } else { var live = packet as LiveNodePacket; if (live == null) { throw new ArgumentException("Unexpected AlgorithmNodeType: " + packet.GetType().Name); } _algorithmNode = new LiveConsoleStatusHandler(live); } _resamplePeriod = _algorithmNode.ComputeSampleEquityPeriod(); //Notification Period for pushes: _notificationPeriod = TimeSpan.FromSeconds(5); }
public SolarLogMonitoringThread(String _URL, ConsoleOutputLogger COL, ConcurrentQueue<SolarLogDataSet> EventQueue, Int32 UpdateTime = 10000) { URL = _URL; SolarLogUpdateTime = UpdateTime; ConsoleOutputLogger = COL; iQueue = EventQueue; }
public async Task ItWorksWithMsmq() { var receivedMessages = new ConcurrentQueue<string>(); var headers = new Dictionary<string, string> { {Headers.TimeToBeReceived, "00:00:04"} }; using (var sendOnlyBus = GetBus(receivedMessages, 0)) { await sendOnlyBus.SendLocal("hej med dig (denne besked bliver ikke modtaget)", headers); await Task.Delay(5000); } using (var receiverBus = GetBus(receivedMessages, 1)) { await receiverBus.SendLocal("hej med dig (det gør den her)", headers); await Task.Delay(2000); } Assert.That(receivedMessages.Count, Is.EqualTo(1), "Expected only one message - got: {0}", string.Join(", ", receivedMessages)); Assert.That(receivedMessages.Single(), Is.EqualTo("hej med dig (det gør den her)")); }
public void ConsumerQueue() { ConcurrentQueue<User> consumerQueue; User user; int allcount = 0; Stopwatch watch = Stopwatch.StartNew(); while (true) { _dataEvent.WaitOne(); if (!_currentQueue.IsEmpty) { _currentQueue = (_currentQueue == _writeQueue) ? _readQueue : _writeQueue; consumerQueue = (_currentQueue == _writeQueue) ? _readQueue : _writeQueue; while (!consumerQueue.IsEmpty) { while (!consumerQueue.IsEmpty) { if (consumerQueue.TryDequeue(out user)) { FluentConsole.White.Background.Red.Line(user.ToString()); allcount++; } } FluentConsole.White.Background.Red.Line($"当前个数{allcount.ToString()},花费了{watch.ElapsedMilliseconds.ToString()}ms;"); System.Threading.Thread.Sleep(20); } } } }
public EventStreamReader(Stream _stream, ConcurrentQueue<String> _queue, AutoResetEvent _emitterWaitHandle, int _sleepTimeMs = 1000) { stream = _stream; queue = _queue; emitterWaitHandle = _emitterWaitHandle; sleepTimeMs = _sleepTimeMs; }
public Playlist(int maxPlayed = 4, int lowCount = 1) { MaxPlayed = maxPlayed; LowPlaylistCount = lowCount; _nextSongs = new ConcurrentQueue<Song>(); _playedSongs = new ConcurrentQueue<Song>(); }
public PacketManager() { m_vIncomingPackets = new ConcurrentQueue<Message>(); m_vOutgoingPackets = new ConcurrentQueue<Message>(); m_vIsRunning = false; }
public SpawnerManager() { this._sceneManager = null; // post init this._spawnRequestConcurrentQueue = new ConcurrentQueue<GameObjectSpawnRequest>(); this._removeGameObjectRequestConcurrentQueue = new ConcurrentQueue<IGameObject>(); this._firstTime = true; }
public void Setup() { queue = new ConcurrentQueue<int>(); for (int i = 0; i < 10; i++) { queue.Enqueue(i); } }
public void CheckinScript(ScriptedPatchRequest request, Jint.JintEngine context) { CachedResult value; if (cacheDic.TryGetValue(request, out value)) { if (value.Queue.Count > 20) return; value.Queue.Enqueue(context); return; } cacheDic.AddOrUpdate(request, patchRequest => { var queue = new ConcurrentQueue<Jint.JintEngine>(); queue.Enqueue(context); return new CachedResult { Queue = queue, Timestamp = SystemTime.UtcNow, Usage = 1 }; }, (patchRequest, result) => { result.Queue.Enqueue(context); return result; }); }
public GSSocket(Socket socket) { this.socket = socket; this.remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint; this.sendQueue = new ConcurrentQueue<byte[]>(); this.isInSending = 0; }
public void RunProcess(Action<Action<StringDictionary>> process, string[] servicePrincipal) { var key = Guid.NewGuid().GetHashCode().ToString("X"); string @namespace = servicePrincipal.Any() ? "Global" : "Local"; _memoryManager.Initialise(@namespace, key, servicePrincipal); _messageQueue = new ConcurrentQueue<byte[]>(); using (_mcb = new MemoryManager.ManagedCommunicationBlock(@namespace, key, MaxMsgSize, -1, servicePrincipal)) using (var processMgmt = new AutoResetEvent(false)) using (var queueMgmt = new AutoResetEvent(false)) using (var environmentKeyRead = new AutoResetEvent(false)) { var handles = new List<WaitHandle> { processMgmt, _mcb.ProfilerRequestsInformation }; ThreadPool.QueueUserWorkItem( SetProfilerAttributes(process, key, @namespace, environmentKeyRead, processMgmt)); ThreadPool.QueueUserWorkItem(SaveVisitData(queueMgmt)); // wait for the environment key to be read if (WaitHandle.WaitAny(new WaitHandle[] {environmentKeyRead}, new TimeSpan(0, 0, 0, 10)) != -1) { ProcessMessages(handles.ToArray()); queueMgmt.WaitOne(); } } }
public AutoSave(RealmManager manager) { Manager = manager; pendings = new ConcurrentQueue<Action<RealmTime>>[5]; for (var i = 0; i < 5; i++) pendings[i] = new ConcurrentQueue<Action<RealmTime>>(); }
public IHandlerResult OnHandlerExecuting(Type messageType, object message) { // First message? Init the bucket and refill timer if (this.tokenBucket == null) { this.tokenBucket = new ConcurrentQueue<byte>(Enumerable.Range(0, this.RatePerSecond).Select(i => (byte)1)); this.delayInterval = TimeSpan.FromMilliseconds(1000 / this.RatePerSecond); this.refillTimer = new Timer((s) => { if (this.tokenBucket.Count < this.RatePerSecond) { this.tokenBucket.Enqueue((byte)1); } }, null, 0, (long)this.delayInterval.TotalMilliseconds); } // Attempt to retrieve a token, if there are none available, delay the message byte token; if (this.tokenBucket.TryDequeue(out token)) { return this.Success(); } else { this.log.Value.InfoFormat("Delivery rate limit exceeded - Redelivering message {0} in {1}ms", message.ToString(), this.delayInterval.TotalMilliseconds); return this.Delay(this.delayInterval); } }
public ComunicationItem(IConnection argConnection) { connection = argConnection; comunicatsToSend = new ConcurrentQueue<Comunicat>(); readedData = new StringBuilder(); readedDatabracketLevel = openBrackets; }
public VideoPacketDecoderWorker(PixelFormat pixelFormat, bool skipFrames, Action<VideoFrame> onFrameDecoded) { _pixelFormat = pixelFormat; _skipFrames = skipFrames; _onFrameDecoded = onFrameDecoded; _packetQueue = new ConcurrentQueue<VideoPacket>(); }
protected override void SetUp() { _activator = Using(new BuiltinHandlerActivator()); _waitedSeconds = new ConcurrentQueue<double>(); _rebusConfigurer = Configure.With(_activator) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "test backoff")) .Options(o => { o.SetBackoffTimes(TimeSpan.FromSeconds(0.2), TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(1)); o.Decorate<ITransport>(c => { var transport = c.Get<ITransport>(); var transportTap = new TransportTap(transport); transportTap.NoMessageReceived += () => { var elapsedSinceStart = DateTime.UtcNow - _busStartTime; var elapsedSeconds = Math.Round(elapsedSinceStart.TotalSeconds, 1); _waitedSeconds.Enqueue(elapsedSeconds); }; return transportTap; }); o.SetMaxParallelism(10); o.SetNumberOfWorkers(1); }); }
internal WSSharpWebSocketEngine(WebSocket parent, string userAgent, int sendInterval) { _parent = parent; _userAgent = userAgent; _sendInterval = sendInterval; _sendQueue = new ConcurrentQueue<string>(); }
private static Map Iterate(ConcurrentQueue<Tuple<Map, char>> queue, Tree tree) { Tuple<Map, char> var; while (!queue.TryDequeue(out var)) System.Threading.Thread.Sleep(5); var currentMap = var.Item1; var cars = currentMap.Parse(); //Console.WriteLine("Checking:\n" + currentMap); if (cars.ContainsKey(Globals.TargetCar) && cars[Globals.TargetCar].Item1.Equals(targetLocation)) return currentMap; foreach (var kvp in cars) if (kvp.Key != var.Item2) { Map move; bool horizontal = kvp.Value.Item3 == Direction.Right; for (int i = 1; i <= (horizontal ? kvp.Value.Item1.X : kvp.Value.Item1.Y); i++) { move = currentMap.makeMove(kvp.Key, kvp.Value.Item1, kvp.Value.Item3.Invert(), kvp.Value.Item2, i); if (move != null) { NewMethod(queue, tree, currentMap, kvp, move); } else break; } for (int i = 1; i < (horizontal ? map.map.GetLength(0) - kvp.Value.Item1.X : map.map.GetLength(1) - kvp.Value.Item1.Y); i++) { move = currentMap.makeMove(kvp.Key, kvp.Value.Item1, kvp.Value.Item3, kvp.Value.Item2, i); if (move != null) { NewMethod(queue, tree, currentMap, kvp, move); } else break; } } if (queue.Count == 0) return Globals.NoSolutions; // We don't have anything to add return null; // no solution found yet }
public LogFileSearch(ITaskScheduler taskScheduler, ILogFile logFile, string searchTerm, TimeSpan maximumWaitTime) { if (taskScheduler == null) throw new ArgumentNullException("taskScheduler"); if (logFile == null) throw new ArgumentNullException("logFile"); if (string.IsNullOrEmpty(searchTerm)) throw new ArgumentException("searchTerm may not be empty"); _logFile = logFile; _filter = new SubstringFilter(searchTerm, true); _matches = new List<LogMatch>(); _syncRoot = new object(); _listeners = new LogFileSearchListenerCollection(this); _pendingModifications = new ConcurrentQueue<LogFileSection>(); _scheduler = taskScheduler; const int maximumLineCount = 1000; _maximumWaitTime = maximumWaitTime; _logLinesBuffer = new LogLine[maximumLineCount]; _matchesBuffer = new List<LogLineMatch>(); _logFile.AddListener(this, _maximumWaitTime, maximumLineCount); _task = _scheduler.StartPeriodic(FilterAllPending, TimeSpan.FromMilliseconds(100), string.Format("Search {0}", logFile)); }
static void Main(string[] args) { TwangManSays("********************************************"); TwangManSays("* HANG THE TWANG *"); TwangManSays("********************************************"); CurrentGames = new Dictionary<long, TwitterThread>(); tweetsToSend = new ConcurrentQueue<SendArgs>(); TwitterSender = new Task(DoWork); TwitterSender.Start(); _sendService = new TwitterService(Authentication.ConsumerKey, Authentication.ConsumerSecret); _sendService.AuthenticateWith(Authentication.AccessToken, Authentication.AccessTokenSecret); _service = new TwitterService(Authentication.ConsumerKey, Authentication.ConsumerSecret); _service.AuthenticateWith(Authentication.AccessToken, Authentication.AccessTokenSecret); TwitterListener = new Task(Listen); TwitterListener.Start(); Console.ReadLine(); _service.CancelStreaming(); }
public static byte[] FillOne(ConcurrentQueue<Operation> writeQueue, ConcurrentQueue<Operation> readQueue) { Operation op; if (!writeQueue.TryDequeue(out op)) return new byte[0]; readQueue.Enqueue(op); return op.Packet; }
private static List<byte> Fill(List<byte> buffer, ConcurrentQueue<Operation> writeQueue, ConcurrentQueue<Operation> readQueue) { Operation op; //at this point there should never be nothing in the queue, but just in case if (!writeQueue.TryPeek(out op)) return buffer; //check if adding the next item in the queue would overflow the buffer if (op.Packet.Length + buffer.Count > _bufferLength) return buffer; //again, if you peeked at it, it should still be here, so you should never hit this if (!writeQueue.TryDequeue(out op)) return buffer; //make sure these two operations happen as transaction var currentIndex = buffer.Count; try { buffer.AddRange(op.Packet); readQueue.Enqueue(op); } catch { //roll it back buffer.RemoveRange(currentIndex, op.Packet.Length); writeQueue.Enqueue(op); } //continue filling the buffer until it's full return Fill(buffer, writeQueue, readQueue); }
public static byte[] Fill(ConcurrentQueue<Operation> writeQueue, ConcurrentQueue<Operation> readQueue) { var fill = Fill(new List<byte>(), writeQueue, readQueue); var buffer = new byte[fill.Count]; fill.CopyTo(buffer, 0); return buffer; }
/// <summary> /// StrongNameCatalog Constructor /// <para> /// Use this Ctor to get all dll's that export anything in the spezific paths /// </para> /// <para> /// Use the <paramref name="trustedKeys" /> params to search for the Public Keys. Only Assambly with one of that keys will included /// Set <code>#DEFINE SECLOADING</code> to Compile this function /// </para> /// </summary> /// <param name="path">The Paths to search</param> /// <param name="watchDirectorys">Set this to True to enable the AutoWatch function </param> /// <param name="trustedKeys">All Public keys that the application should trust</param> public StrongNameCatalog(IEnumerable<string> path, bool watchDirectorys, params byte[][] trustedKeys) { _paths = path; _watchDirectorys = watchDirectorys; _trustedKeys = trustedKeys; LowPriorityList = new ConcurrentQueue<string>(); }
/// <summary> /// Event journal class /// </summary> public EventJournal() { m_MessageList = new ConcurrentQueue <LogItem>(); m_ListEvent = new AutoResetEvent(false); }
public MyMessageHandler(IBus bus, ConcurrentQueue <DateTime> messages) { _bus = bus; _sentMessages = messages; }
public SendQueue() { _pending = new ConcurrentQueue <Gram>(); }
private void ClearQueuedOutput() { // NOTE: This may run on a background thread! this.outputQueue = new ConcurrentQueue <string>(); }
public ThreadAnonymousClass(ThreadedIndexingAndSearchingTestCase outerInstance, LineFileDocs docs, long stopTime, ISet <string> delIDs, ISet <string> delPackIDs, ConcurrentQueue <SubDocs> allSubDocs) { this.outerInstance = outerInstance; this.docs = docs; this.stopTime = stopTime; this.delIDs = delIDs; this.delPackIDs = delPackIDs; this.allSubDocs = allSubDocs; }
private async Task Run() { Google.Apis.Services.BaseClientService.Initializer bcs = new Google.Apis.Services.BaseClientService.Initializer(); bcs.ApiKey = settings.ApiKey; bcs.ApplicationName = "Intersect Updater"; bcs.GZipEnabled = true; Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(bcs); await CheckFilesRecursively(service, "", settings.FolderId); lbl.MeasureString = null; var updating = UpdateList.Count > 0; FilesToDownload = UpdateList.Count; CheckingForUpdates = false; if (UpdateList.Count > 0) { List <Update> updates = new List <Update>(); updates.AddRange(UpdateList); UpdateList = new ConcurrentQueue <Update>(); var updatePaths = new HashSet <string>(); for (int i = 0; i < updates.Count; i++) { if (!string.IsNullOrEmpty(settings.Background)) { var backgroundpath = Path.GetFullPath(settings.Background); var updatePath = Path.GetFullPath(updates[i].FilePath); if (backgroundpath == updatePath) { var update = updates[i]; updates.Remove(updates[i]); updatePaths.Add(update.FilePath); UpdateList.Enqueue(update); break; } } } var updatesToRemove = new List <Update>(); foreach (var update in updates) { if (!updatePaths.Contains(update.FilePath)) { updatePaths.Add(update.FilePath); } else { updatesToRemove.Add(update); } } foreach (var update in updatesToRemove) { updates.Remove(update); } foreach (var update in updates) { UpdateList.Enqueue(update); } BeginInvoke((Action)(() => UpdateStatus())); for (int i = 0; i < UpdateThreads.Length; i++) { UpdateThreads[i] = new Thread(DownloadFiles); UpdateThreads[i].Start(); } } var threadsRunning = true; while (threadsRunning && updating) { threadsRunning = false; foreach (var thread in UpdateThreads) { if (thread.IsAlive) { threadsRunning = true; } break; } Application.DoEvents(); } if (updating) { BeginInvoke((Action)(() => lbl.Text = @"Update complete! Launching game!")); } else { BeginInvoke((Action)(() => lbl.Text = @"No updates found! Launching game!")); } //Launch Game await Wait(); string AssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).ToString(); var path = Path.Combine(AssemblyPath, settings.LaunchApplication); var workingDir = Path.GetDirectoryName(path); var psi = new ProcessStartInfo(path); psi.WorkingDirectory = workingDir; Process.Start(psi); BeginInvoke((Action)(() => Close())); }
/// <summary> /// Constructor /// </summary> public AbstractEventAggregator() { Queue = new ConcurrentQueue <ApiEventData>(); }
public LogicStation() { WaitingLine = new ConcurrentQueue <Plane>(); ChangeInState += PushToWait; }
public ReceiverLossList() { backingList = new ConcurrentQueue <ReceiverLossListEntry>(); keys = new Dictionary <ReceiverLossListEntry, string>(32); removeKeys = new Dictionary <ReceiverLossListEntry, string>(); }
private static void CleanQueue( Func <ApiEventData, bool> removeIf) { Queue = new ConcurrentQueue <ApiEventData>( Queue.Where(item => !removeIf(item))); }
protected override void Add(ConcurrentQueue<T> collection, int index, T value) { collection.Enqueue(value); }
public WorkPool(IModel model) { actions = new ConcurrentQueue <Action>(); tokenSource = new CancellationTokenSource(); }
public ProxyQueue(string pr, ProxyType type) { Type = type; SafeUpdate(pr); proxies = new ConcurrentQueue <ProxyClient>(plist); }
public EventLoop() { _events = new ConcurrentQueue <EventPublication>(); _cancellationToken = new CancellationTokenSource(); }
protected GameThread() { Log.Trace(); _invokeQueue = new ConcurrentQueue <Action>(); _gameThread = new Task(_run, TaskCreationOptions.LongRunning); }
protected override int? GetCount(ConcurrentQueue<T> sequence) { return sequence.Count; }
public Task <IJobResult> RunAsync() { jobStatusQueue = new ConcurrentQueue <TaskCommandStatus>(); return(DoRunAsync()); }
public SomeSaga(ConcurrentQueue <int> registeredRevisions) { _registeredRevisions = registeredRevisions; }
public LongRunningTaskScheduler(ApartmentState apartmentState) { _apartmentState = apartmentState; _threads = new ConcurrentQueue <Thread>(); _tasks = new ConcurrentQueue <Task>(); }
public void Dispose() { _disposed = true; //_queue.Clear(); _queue = null; }
public MockStopwatch(string tag, TimeSpan elapsed, TimeLineProvider timelineProvider, ConcurrentQueue <IAsyncTimedEvent> timeline) { Tag = tag; _timelineProvider = timelineProvider; _timeline = timeline; Elapsed = elapsed; }
public void Flush() { _ordersQueue = new ConcurrentQueue <CalculationOrder>(); _finishedOrders.Clear(); }