protected override void OnStart(string[] args) { m = new Monitor(true); m.StandardErrorOut += m_StandardErrorOut; m.StandardOut += m_StandardOut; m.Start(); }
public override string ToString() { g = (Monitor)base.Tag; Binding myBinding = new Binding("ext"); myBinding.Mode = BindingMode.TwoWay; myBinding.Source = g; txtext.SetBinding(TextBox.TextProperty, myBinding); Binding myBinding2 = new Binding("basename"); myBinding2.Mode = BindingMode.TwoWay; myBinding2.Source = g; txtbase.SetBinding(TextBox.TextProperty, myBinding2); Binding myBinding3 = new Binding("flags"); myBinding3.Mode = BindingMode.TwoWay; myBinding3.Source = g; txtflags.SetBinding(TextBox.TextProperty, myBinding3); Binding descbinding = new Binding("Description"); descbinding.Mode = BindingMode.TwoWay; descbinding.Source = g; txtdesc.SetBinding(TextBox.TextProperty, descbinding); return base.ToString(); }
private static void Main(string[] args) { //string filename = // @"..\..\..\Dev.ProcessMonitor.TestTargerExe\bin\Debug\Dev.ProcessMonitor.TestTargerExe.exe"; //string arg = ""; ////string filename = //// @"..\..\..\Dev.ProcessMonitor.FormTest\bin\Debug\Dev.ProcessMonitor.FormTest.exe"; ////string arg = ""; //var starter = new ProcessStarterAsyn(filename, arg); //starter.StandardErrorOut += starter_StandardErrorOut; //starter.StandardOut += starter_StandardOut; //starter.StartAsyn(); //Console.WriteLine("pressanykey"); var m = new Monitor(true); m.StandardErrorOut += m_StandardErrorOut; m.Start(); Console.ReadKey(); m.Stop(); }
//public void AddBattery(Battery battery) //{ // using (var db = new ShopContext()) // { // var tmp = (from entity in db.Carts // where entity.GoodsId == battery.Id // where entity.GoodsCategory == "battery" // select entity).FirstOrDefault(); // if (tmp == null) // { // var cart = new Cart // { // GoodsId = battery.Id, // GoodsCategory = "battery", // Price = battery.Price, // Count = 1 // }; // db.Carts.Add(cart); // } // else // { // tmp.Count++; // db.Entry(tmp).State = EntityState.Modified; // } // db.SaveChanges(); // } //} public void AddMonitor(Monitor monitor, List<Cart> list) { var cart = new Cart { GoodsId = monitor.Id, GoodsCategory = "Monitors", Price = monitor.Price, Count = 1 }; var flg = 1; foreach (Cart item in list) { if (item.GoodsId == monitor.Id && item.GoodsCategory == "Monitors") { item.Count++; flg = 0; break; } } if (flg == 1) { list.Add(cart); } }
/// <summary> /// Parses the specified contexts and re-populates context array with features and returns /// the values for these features. /// If all values are unspecified, then null is returned. /// </summary> /// <param name="contexts">The contexts.</param> /// <param name="monitor">The evaluation monitor.</param> /// <returns>The event values.</returns> /// <exception cref="System.InvalidOperationException">Negative values are not allowed: context</exception> public static float[] ParseContexts(string[] contexts, Monitor monitor) { var hasRealValue = false; var values = new float[contexts.Length]; for (var ci = 0; ci < contexts.Length; ci++) { var ei = contexts[ci].LastIndexOf("=", StringComparison.InvariantCulture); if (ei > 0 && ei + 1 < contexts[ci].Length) { var gotReal = true; try { values[ci] = float.Parse(contexts[ci].Substring(ei + 1), CultureInfo.InvariantCulture); } catch (Exception) { gotReal = false; if (monitor != null) monitor.OnError("Unable to determine value in context:" + contexts[ci]); values[ci] = 1; } if (gotReal) { if (values[ci] < 0) { throw new InvalidOperationException("Negative values are not allowed: " + contexts[ci]); } contexts[ci] = contexts[ci].Substring(0, ei); hasRealValue = true; } } else { values[ci] = 1; } } if (!hasRealValue) { values = null; } return values; }
/// <summary> /// Initializes a new instance of the <see cref="OnePassDataIndexer"/> class, using a event stream, a cutoff value and a value that indicates if the events should be sorted. /// </summary> /// <param name="eventStream">The event stream.</param> /// <param name="cutoff">The cutoff.</param> /// <param name="sort">if set to <c>true</c> the events will be sorted during the indexing.</param> /// <param name="monitor">The evaluation monitor.</param> public OnePassDataIndexer(IObjectStream<Event> eventStream, int cutoff, bool sort, Monitor monitor) : base(monitor) { EventStream = eventStream; Cutoff = cutoff; Sort = sort; }
public MonitorAdorner(HeliosVisualView adornedElement, string monitorLabel, Monitor monitor) : base(adornedElement) { _textFormat.VerticalAlignment = TextVerticalAlignment.Center; _label = monitorLabel; _monitor = monitor; }
public override void SetMonitor(Monitor mon) { foreach (Solver t in solvers) { t.SetMonitor(mon); } }
public static int Main(String[] args) { Monitor monitor = new Monitor(); SocketListener listener = new SocketListener(monitor); listener.startListening(); return 0; }
public MainPage() { this.InitializeComponent (); this.teams = new TeamCollection (); this.attacks = new AttackCollection (this.LayoutCanvas); this.allocators = new AllocatorClassifier (new [] { typeof (CircleAllocator), typeof (RectangleAllocator), typeof (GridAllocator) }); this.monitor = new Monitor (); this.lock_object = new object (); this.service_names = new List <string> (); this.windowSize = new Size (this.LayoutCanvas.Width, this.LayoutCanvas.Height); this.speed = (int) this.speedSlider.Value + 1; this.realtimeMode = this.realtime.IsChecked == true; this.begin_with_realtime = false; this.play_iter = 0; this.update_interval = 10; foreach (var allocator in this.allocators) this.Allocation.Items.Add (allocator.Name); this.Allocation.SelectedIndex = this.allocators.Index; }
static void Init(string programPath) { client = new TenhouClient("aixile"); gameEnd.Reset(); client.OnLogin += () => { //client.EnterLobby(0); client.Join(GameType.North); client.Join(GameType.North_fast); client.Join(GameType.East); client.Join(GameType.East_fast); }; client.OnGameEnd += () => { gameEnd.Set(); }; client.OnClose += () => { gameEnd.Set(); }; monitor = new Monitor(client); monitor.Start(); controller = new Controller(client, programPath); controller.Start(); client.Login(); }
public HandsRecognition(Monitor mon) { m_images = new Queue<PXCMImage>(); this.mon = mon; LUT = Enumerable.Repeat((byte)0, 256).ToArray(); LUT[255] = 1; }
public void Setup() { buildFactoryFake = new BuildFactoryFake(); buildRepositoryFake = new BuildRepositoryFake(); solutionBuildFake = new SolutionBuildFake(); buildFactoryFake.Build = solutionBuildFake; monitor = new Monitor(buildFactoryFake, buildRepositoryFake); }
private void button4_Click(object sender, EventArgs e) { var m = new Monitor(true); m.StandardErrorOut += starter_StandardErrorOut; m.StandardOut += starter_StandardOut; m.Start(); }
public Program() { Computer comp = new Computer(); comp = new Disk( comp ); comp = new Monitor( comp ); comp = new CD( comp ); comp = new CD( comp ); Console.WriteLine( comp.Description() ); }
private static void Main() { using (var monitor = new Monitor("c:\\foobar", "*.dll")) { monitor.Start(); // breakpoints in your actual service should not be hit :) } }
public Service1() { m = new Monitor(false); Setting.AttachLog(new ObserverLogToLog4net()); InitializeComponent(); }
public StartCommand(Monitor monitor, Func<Machine> getCurrentMachine, IncludeFileCommand includeCommand) : base(monitor, "start", "starts the emulation.", "s") { if(includeCommand == null) { throw new ArgumentException("includeCommand cannot be null.", "includeCommand"); } GetCurrentMachine = getCurrentMachine; IncludeCommand = includeCommand; }
public BuildMonitorPackage() { Settings.CreateApplicationFolderIfNotExist(); var factory = new BuildFactory(); var repository = new BuildRepository(Settings.RepositoryPath); monitor = new Monitor(factory, repository); dataAdjuster = new DataAdjusterWithLogging(repository, PrintLine); }
//Builder public MonitorThread(Monitor monitor, bool running) { this.monitor = monitor; this.suspensionLvl = 0; this.serviceMgr = new ServiceTools(); this.suspendMtx = new Mutex(); if (!running) SuspendThread(); }
static void Main(string[] args) { Console.Title = "果园的监控"; Orchard orchard = new Orchard(); //创建果园实例 IMonitor bjMonitor = new Monitor(orchard, "北京果园监控员");//北京果园监控员 IMonitor shMonitor = new Monitor(orchard, "上海果园监控员");//上海果园监控员 orchard.State = "苹果园!"; //将果园监控状态改为苹果园 orchard.Notify(); //通知监控员更新监控状态 Console.Read(); }
public MonitorResetItem(Monitor oldMonitor, int oldId, int newId) { _controls = new List<HeliosVisual>(); _oldMonitor = oldMonitor; _oldId = oldId; _newMonitor = newId; _oldWidth = oldMonitor.Width; _oldHeight = oldMonitor.Height; _scale = true; }
public Service() { //m = new Monitor(false); m = new Monitor(true); m.StandardErrorOut += m_StandardErrorOut; m.StandardOut += m_StandardOut; //Setting.SetLogSeverity(LogSeverity.Info); Setting.AttachLog(new ObserverLogToLog4net()); InitializeComponent(); }
/// <summary> /// Make a new object, associating it with a role. /// </summary> void Make(Monitor.Role role) { if (null != prefab) { Vector3 at = new Vector3(Random.value * 10f - 5f, 0.5f, Random.value * 10f - 5f); GameObject o = (GameObject)Instantiate(prefab, at, Quaternion.identity); MonitorTag tag = o.GetComponent<MonitorTag>(); if (null != tag) { tag.role = role; _monitor.ActivateMonitor(role, o); } } }
public Client(Socket socket, Monitor monitor) { _listOfItemsInAuction = new List<Item>(); makeItems(); this._socket = socket; this._monitor = monitor; this._clientInRoom = false; networkStream = new NetworkStream(_socket); streamReader = new StreamReader(networkStream); streamWriter = new StreamWriter(networkStream); monitor.AddStreamWriter(streamWriter); }
static void Main() { var teamFlashConfig = LoadConfig(); teamFlashConfig.ServerUrl = ReadConfig("TeamCity URL", teamFlashConfig.ServerUrl); teamFlashConfig.Username = ReadConfig("Username", teamFlashConfig.Username); var password = ReadConfig("Password", ""); teamFlashConfig.BuildTypeIds = ReadConfig("Comma separated build type ids (eg, \"bt64,bt12\"), or * for all", teamFlashConfig.BuildTypeIds); SaveConfig(teamFlashConfig); Console.Clear(); var buildTypeIds = teamFlashConfig.BuildTypeIds == "*" ? new string[0] : teamFlashConfig.BuildTypeIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); var monitor = new Monitor(); TurnOffLights(monitor); while (!Console.KeyAvailable) { var lastBuildStatus = RetrieveBuildStatus( teamFlashConfig.ServerUrl, teamFlashConfig.Username, password, buildTypeIds); switch (lastBuildStatus) { case BuildStatus.Unavailable: TurnOffLights(monitor); Console.WriteLine(DateTime.Now.ToShortTimeString() + " Server unavailable"); break; case BuildStatus.Passed: TurnOnSuccessLight(monitor); Console.WriteLine(DateTime.Now.ToShortTimeString() + " Passed"); break; case BuildStatus.Investigating: TurnOnWarningLight(monitor); Console.WriteLine(DateTime.Now.ToShortTimeString() + " Investigating"); break; case BuildStatus.Failed: TurnOnFailLight(monitor); Console.WriteLine(DateTime.Now.ToShortTimeString() + " Failed"); break; } Wait(); } TurnOffLights(monitor); }
public TagScreen(Monitor parent, int tag) { activeLayout = Manager.GetLayoutIndexFromName(Manager.settings.ReadSettingOrDefault("DefaultLayout", parent.SafeName, (tag).ToString(), "DefaultLayout")); _parent = parent; _tag = tag; _controlled = _parent.Controlled; InitLayout(); Manager.WindowCreate += Manager_WindowCreate; Manager.WindowDestroy += Manager_WindowDestroy; }
// // GET: /MonitoringLV/Create public string Create(int id,int status,float current, float voltage) { var db = new HefestoDevicesEntities(); Monitor mon = new Monitor(); mon.Monitor_Device = id; mon.Monitor_Date = DateTime.Now; mon.Monitor_Status = status; mon.Monitor_Current = current; mon.Monitor_Voltage = voltage; db.Monitor.Add(mon); db.SaveChanges(); return "OK"; }
static void Main() { Console.Write("TeamCity URL:"); var serverUrl = Console.ReadLine(); Console.Write("Username:"******"Password:"******" Server unavailable"); break; case BuildStatus.Passed: TurnOnSuccessLight(monitor); Console.WriteLine(DateTime.Now.ToShortTimeString() + " Passed"); break; case BuildStatus.Investigating: TurnOnWarningLight(monitor); Console.WriteLine(DateTime.Now.ToShortTimeString() + " Investigating"); break; case BuildStatus.Failed: TurnOnFailLight(monitor); Console.WriteLine(DateTime.Now.ToShortTimeString() + " Failed"); break; } Wait(); } TurnOffLights(monitor); }
public static List<Monitor> EnumerateMonitors() { List<Monitor> monitors = new List<Monitor>(); var displayDevices = EnumerateDesktopDisplayDevices(); foreach (var displayDevice in displayDevices) { var availableDisplaySettings = EnumerateAllDisplaySettings(displayDevice.DeviceName); var currentDisplaySettings = EnumerateCurrentDisplaySettings(displayDevice.DeviceName); var monitor = new Monitor(displayDevice, currentDisplaySettings, availableDisplaySettings); monitors.Add(monitor); } return monitors; }
public void Dispose() { Monitor.Exit(mutex); }
internal void ReleaseLock() { Monitor.Exit(_lockObject); }
internal void ExitLock() { Monitor.Exit(InstanceMutationLock); }
public static void WorkerMainThread(ClientWorkerData p_worker_data, IPEndPoint p_server_ip_endpoint) { ClientWorkerData worker_data = p_worker_data; Dictionary <int, Thread> all_mini_threads = new Dictionary <int, Thread>(); object all_mini_threads_lock = new object(); ClientWorkerStatus status = ClientWorkerStatus.Connecting; System.Timers.Timer worker_quick_check_timer_object = new System.Timers.Timer(); worker_quick_check_timer_object.Interval = 13500; worker_quick_check_timer_object.AutoReset = false; worker_quick_check_timer_object.Elapsed += new System.Timers.ElapsedEventHandler((sender, e) => worker_timer_Elapsed(sender , e, worker_data.send_to_worker_construct , worker_data.client_worker_pulse_object)); ClientWorkerTimer timer = new ClientWorkerTimer(worker_quick_check_timer_object); Socket server_socket = new Socket(SocketType.Stream, ProtocolType.Tcp); int k = 0; while (k < 4) { try { server_socket.Connect(p_server_ip_endpoint); k = 0; break; } catch (Exception) { k++; Thread.Sleep(200); continue; } } if (k > 3) { MessageFromWorker signal_reject_message = new MessageFromWorker(new ClientWorkerSignal(false), TypeOfMessageFromWorker.SignalMessage); AddNewTransferMiniThread(signal_reject_message, worker_data.receive_from_worker_construct, worker_data.message_received_inform , worker_data.main_form_invoke, all_mini_threads, all_mini_threads_lock); try { server_socket.Shutdown(SocketShutdown.Both); server_socket.Close(); } catch { } Thread.CurrentThread.Abort(); return; } MessageFromWorker signal_accept_message = new MessageFromWorker(new ClientWorkerSignal(true), TypeOfMessageFromWorker.SignalMessage); AddNewTransferMiniThread(signal_accept_message, worker_data.receive_from_worker_construct, worker_data.message_received_inform , worker_data.main_form_invoke, all_mini_threads, all_mini_threads_lock); int last_message_sent_id = 0; bool cancelled = false; bool user_cancelled = false; BinaryFormatter formatter = new BinaryFormatter(); formatter.Context = new StreamingContext(StreamingContextStates.All); formatter.TypeFormat = FormatterTypeStyle.TypesWhenNeeded; formatter.AssemblyFormat = FormatterAssemblyStyle.Simple; SerializationBinder serialization_binder = formatter.Binder; MemoryStream stream = new MemoryStream(); byte[] data_buffer = new byte[1]; status = ClientWorkerStatus.Satrting; Queue <byte[]> temp_receive_thread_queue = new Queue <byte[]>(); WorkerReceiveThreadConstruct receive_thread_construct = new WorkerReceiveThreadConstruct(temp_receive_thread_queue); Thread receiver_thread = new Thread(() => ReceiveThread(receive_thread_construct, ref server_socket , ref timer, worker_data.client_worker_pulse_object)); Queue <KeyValuePair <TypeOfSend, byte[]> > send_thread_queue = new Queue <KeyValuePair <TypeOfSend, byte[]> >(); bool send_thread_queue_flag = false; bool send_thread_cancel_flag = false; object send_thread_pulse_object = new object(); bool send_thread_receipt_received_flag = false; Thread send_thread = new Thread(() => SendThread(send_thread_queue, ref send_thread_queue_flag, ref send_thread_cancel_flag , ref send_thread_receipt_received_flag, send_thread_pulse_object, worker_data.client_worker_pulse_object, receive_thread_construct, server_socket, timer)); receiver_thread.Start(); send_thread.Start(); timer.StartAndReset(); status = ClientWorkerStatus.Normal; while (true) { lock (worker_data.client_worker_pulse_object) { if (!worker_data.cancel_construct.cancel_construct_flag && !receive_thread_construct.receive_thread_queue_flag && !worker_data.send_to_worker_construct.send_to_worker_queue_flag) { Monitor.Wait(worker_data.client_worker_pulse_object); } if (worker_data.cancel_construct.cancel_construct_flag) { timer.PrimerStop(); user_cancelled = true; cancelled = true; break; } if (receive_thread_construct.receive_thread_queue_flag) { if (receive_thread_construct.receive_thread_queue.Count > 0) { byte[] byte_received_data = receive_thread_construct.receive_thread_queue.Dequeue(); if (receive_thread_construct.receive_thread_queue.Count == 0) { receive_thread_construct.receive_thread_queue_flag = false; } if (byte_received_data.Length == 0) { timer.PrimerStop(); MessageFromWorker cancel_message_from_worker = new MessageFromWorker(null, TypeOfMessageFromWorker.OfflineInform); AddNewTransferMiniThread(cancel_message_from_worker, worker_data.receive_from_worker_construct, worker_data.message_received_inform , worker_data.main_form_invoke, all_mini_threads, all_mini_threads_lock); cancelled = true; break; } else { stream = new MemoryStream(byte_received_data); DataForSend data_received = null; try { data_received = (DataForSend)formatter.Deserialize(stream); } catch { stream = new MemoryStream(); continue; } stream = new MemoryStream(); if (data_received.Get_data_for_send_type == TypeOfDataForSend.QuickAnswer && status == ClientWorkerStatus.WaitForAReceipt) { QuickAnswer received_quick_answer = null; try { received_quick_answer = ((QuickAnswer)data_received.Get_message_object); } catch { continue; } if (received_quick_answer.Get_id == last_message_sent_id) { lock (send_thread_pulse_object) { send_thread_receipt_received_flag = true; Monitor.Pulse(send_thread_pulse_object); status = ClientWorkerStatus.Normal; } } } else if (data_received.Get_data_for_send_type == TypeOfDataForSend.QuickCheck) { QuickCheck received_quick_check = null; try { received_quick_check = ((QuickCheck)data_received.Get_message_object); } catch { continue; } QuickAnswer quick_answer = new QuickAnswer(received_quick_check.Get_id); DataForSend quick_answer_for_send = new DataForSend(TypeOfDataForSend.QuickAnswer, quick_answer); formatter.Serialize(stream, quick_answer_for_send); byte[] byte_quick_answer = stream.GetBuffer(); stream = new MemoryStream(); lock (send_thread_pulse_object) { send_thread_queue.Enqueue(new KeyValuePair <TypeOfSend, byte[]>(TypeOfSend.WithoutReceipt, byte_quick_answer)); send_thread_queue_flag = true; Monitor.Pulse(send_thread_pulse_object); } } else if (data_received.Get_data_for_send_type == TypeOfDataForSend.UserMessage) { UserMessageToClient user_message = null; try { user_message = ((UserMessageToClient)data_received.Get_message_object); } catch (Exception) { continue; } FinalMessageForClient client_object = null; try { client_object = new FinalMessageForClient(user_message.Get_user_message.Get_message_type, user_message.Get_user_message.Get_message_object); } catch (Exception) { continue; } MessageFromWorker final_message_received = new MessageFromWorker(client_object, TypeOfMessageFromWorker.FinalMessage); AddNewTransferMiniThread(final_message_received, worker_data.receive_from_worker_construct, worker_data.message_received_inform , worker_data.main_form_invoke, all_mini_threads, all_mini_threads_lock); QuickAnswer user_message_answer = new QuickAnswer(user_message.Get_id); DataForSend user_answer_for_send = new DataForSend(TypeOfDataForSend.QuickAnswer, user_message_answer); formatter.Serialize(stream, user_answer_for_send); lock (send_thread_pulse_object) { send_thread_queue.Enqueue(new KeyValuePair <TypeOfSend, byte[]>(TypeOfSend.WithoutReceipt, stream.GetBuffer())); send_thread_queue_flag = true; Monitor.Pulse(send_thread_pulse_object); } stream = new MemoryStream(); } } } else { receive_thread_construct.receive_thread_queue_flag = false; } } if (worker_data.send_to_worker_construct.send_to_worker_queue_flag) { if (status == ClientWorkerStatus.Normal) { if (worker_data.send_to_worker_construct.send_to_worker_queue.Count > 0) { MessageToWorker object_to_send = worker_data.send_to_worker_construct.send_to_worker_queue.Dequeue(); if (worker_data.send_to_worker_construct.send_to_worker_queue.Count == 0) { worker_data.send_to_worker_construct.send_to_worker_queue_flag = false; } if (object_to_send.Get_type_of_message_to_worker_object == TypeOfMessageToWorker.QuickCheckRequest) { QuickCheck quick_check_to_send = new QuickCheck(HelperFunctions.GetGUID()); DataForSend client_data = new DataForSend(TypeOfDataForSend.QuickCheck, quick_check_to_send); formatter.Serialize(stream, client_data); byte[] byte_client_data = stream.GetBuffer(); lock (send_thread_pulse_object) { send_thread_queue.Enqueue(new KeyValuePair <TypeOfSend, byte[]>(TypeOfSend.WithReceipt, byte_client_data)); send_thread_queue_flag = true; Monitor.Pulse(send_thread_pulse_object); } last_message_sent_id = quick_check_to_send.Get_id; status = ClientWorkerStatus.WaitForAReceipt; stream = new MemoryStream(); } else if (object_to_send.Get_type_of_message_to_worker_object == TypeOfMessageToWorker.FinalMessage) { FinalMessageForServer final_message = (FinalMessageForServer)object_to_send.Get_message_for_worker_object; UserMessageToServer user_message_to_send = new UserMessageToServer(HelperFunctions.GetGUID(), final_message); DataForSend client_data = new DataForSend(TypeOfDataForSend.UserMessage, user_message_to_send); formatter.Serialize(stream, client_data); byte[] byte_client_data = stream.GetBuffer(); lock (send_thread_pulse_object) { send_thread_queue.Enqueue(new KeyValuePair <TypeOfSend, byte[]>(TypeOfSend.WithReceipt, byte_client_data)); send_thread_queue_flag = true; Monitor.Pulse(send_thread_pulse_object); } last_message_sent_id = user_message_to_send.Get_id; status = ClientWorkerStatus.WaitForAReceipt; stream = new MemoryStream(); } } else { worker_data.send_to_worker_construct.send_to_worker_queue_flag = false; } } } } } if (cancelled) { timer.PrimerStop(); if (!user_cancelled) { MessageFromWorker offline_inform_message = new MessageFromWorker(null, TypeOfMessageFromWorker.OfflineInform); AddNewTransferMiniThread(offline_inform_message, worker_data.receive_from_worker_construct, worker_data.message_received_inform , worker_data.main_form_invoke, all_mini_threads, all_mini_threads_lock); } try { receiver_thread.Abort(); } catch { } try { server_socket.Shutdown(SocketShutdown.Both); server_socket.Close(); } catch { } receiver_thread.Join(); lock (send_thread_pulse_object) { send_thread_cancel_flag = true; Monitor.Pulse(send_thread_pulse_object); } send_thread.Join(); Thread.CurrentThread.Abort(); return; } }
/// <summary> /// Downloads all the modules specified to the cache. /// Even if modules share download URLs, they will only be downloaded once. /// Blocks until the download is complete, cancelled, or errored. /// </summary> public void DownloadModules( NetFileCache cache, IEnumerable <CkanModule> modules ) { var unique_downloads = new Dictionary <Uri, CkanModule>(); // Walk through all our modules, but only keep the first of each // one that has a unique download path. foreach (CkanModule module in modules.Where(module => !unique_downloads.ContainsKey(module.download))) { unique_downloads[module.download] = module; } this.modules.AddRange(unique_downloads.Values); // Attach our progress report, if requested. onCompleted = (_uris, paths, errors) => ModuleDownloadsComplete(cache, _uris, paths, errors); // Start the download! Download(unique_downloads.Keys); // The Monitor.Wait function releases a lock, and then waits until it can re-acquire it. // Elsewhere, our downloading callback pulses the lock, which causes us to wake up and // continue. lock (download_complete_lock) { log.Debug("Waiting for downloads to finish..."); Monitor.Wait(download_complete_lock); } // If the user cancelled our progress, then signal that. if (downloadCanceled) { foreach (var download in downloads) { download.agent.CancelAsync(); } throw new CancelledActionKraken("Download cancelled by user"); } // Check to see if we've had any errors. If so, then release the kraken! List <Exception> exceptions = downloads .Select(x => x.error) .Where(ex => ex != null) .ToList(); // Let's check if any of these are certificate errors. If so, // we'll report that instead, as this is common (and user-fixable) // under Linux. if (exceptions.Any(ex => ex is WebException && Regex.IsMatch(ex.Message, "authentication or decryption has failed"))) { throw new MissingCertificateKraken(); } if (exceptions.Count > 0) { throw new DownloadErrorsKraken(exceptions); } // Yay! Everything worked! }
private void DrawSeeds(object sender, RenderedWorldEventArgs args) { // ignore if player hasn't loaded a save yet if (!Context.IsWorldReady) { return; } SpriteBatch b = args.SpriteBatch; foreach (var kv in player.currentLocation.terrainFeatures.Pairs) { if (kv.Value is Tree tree) { //Monitor.Log("Found a tree"); int doDraw = -1; //if (terrainFeature.GetType().IsInstanceOfType(new Tree())) if (tree.hasSeed.Value && !tree.stump.Value && (IsMultiplayer || player.ForagingLevel > 0)) { Monitor.Log("found a valid tree"); /* * bushyTree = 1; oak * leafyTree = 2; maple * pineTree = 3; pine * winterTree1 = 4; oak * winterTree2 = 5; maplewwww * palmTree = 6; palm */ int type = tree.treeType.Value; switch (type) { case 1: case 4: doDraw = 309; break; case 2: case 5: doDraw = 310; break; case 3: doDraw = 311; break; case 6: doDraw = 88; break; } var drawObject = seedObjects[doDraw]; Monitor.Log("drawing object " + doDraw); drawObject.drawInMenu(b, Game1.GlobalToLocal(Game1.viewport, new Vector2(kv.Key.X * 64, kv.Key.Y * 64)), 0.8f, 0.5f, 1, false, Color.White, false); } break; } } }
/// <summary> /// Two argument constructor for DataIndexer. /// </summary> /// <param name="eventStream">An event stream which contains the a list of all the Events seen in the training data.</param> /// <param name="cutoff">The minimum number of times a predicate must have been observed in order to be included in the model.</param> /// <param name="sort">if set to <c>true</c> the events will be sorted.</param> /// <param name="monitor"> /// A evaluation monitor that can be used to listen the evaluation messages or it can cancel the indexing operation. /// This argument can be a <c>null</c> value. /// </param> public TwoPassDataIndexer(IObjectStream <Event> eventStream, int cutoff, bool sort, Monitor monitor) : base(monitor) { EventStream = eventStream; Cutoff = cutoff; Sort = sort; }
public void Run(IEnumerable <Action> actions) { // NOTE: This method has been optimized to minimize the total stack depth of the action // by inlining blocks on the critical path that had previously been factored out. if (actions == null) { throw new ArgumentNullException("actions"); } // Copy the queue of actions to process from the enumeration. var actionQueue = new Queue <Action>(); foreach (Action action in actions) { if (action == null) { throw new ArgumentNullException("actions"); } actionQueue.Enqueue(action); } // Short-circuit when no actions to run to satisfy our invariant for pending work sets. if (actionQueue.Count == 0) { return; } // Add this work set to the list of pending work sets. WorkSet workSet; lock (syncRoot) { workSet = new WorkSet(actionQueue); pendingWorkSets.AddLast(workSet); activeThreads += 1; } // Loop until all actions in this work set are finished. for (; ;) { Action nextAction; lock (syncRoot) { // Synchronize and exit if this work set is finished. if (!workSet.SyncHasPendingActions()) { activeThreads -= 1; while (workSet.SyncHasActionsInProgress()) { Monitor.Wait(syncRoot); } return; } // Prepare next action from this work set only. nextAction = workSet.SyncPrepareNextAction(); // Remove the work set from the list of pending work sets if it has no other pending actions. if (!workSet.SyncHasPendingActions()) { pendingWorkSets.Remove(workSet); } // Spawn more threads if needed for pending work sets. SyncSpawnBackgroundActionLoopIfNeeded(); } // Run the next action. try { nextAction(); } catch (Exception ex) { ReportUnhandledException(ex); } finally { lock (syncRoot) { workSet.SyncActionFinished(); Monitor.PulseAll(syncRoot); } } } }
public void unFreezeProcess() { Monitor.Exit(this); }
public void freezeProcess() { Monitor.Enter(this); }
/// <summary>Schedules the processing worker if one hasn't already been scheduled.</summary> private void EnsureWorkerIsRunning() { Debug.Assert(Monitor.IsEntered(_incomingRequests), "Needs to be called under _incomingRequests lock"); if (_runningWorker == null) { VerboseTrace("MultiAgent worker queued"); // Create pipe used to forcefully wake up curl_multi_wait calls when something important changes. // This is created here rather than in Process so that the pipe is available immediately // for subsequent queue calls to use. Debug.Assert(_wakeupRequestedPipeFd == null, "Read pipe should have been cleared"); Debug.Assert(_requestWakeupPipeFd == null, "Write pipe should have been cleared"); unsafe { int* fds = stackalloc int[2]; Interop.CheckIo(Interop.Sys.Pipe(fds)); _wakeupRequestedPipeFd = new SafeFileHandle((IntPtr)fds[Interop.Sys.ReadEndOfPipe], true); _requestWakeupPipeFd = new SafeFileHandle((IntPtr)fds[Interop.Sys.WriteEndOfPipe], true); } // Kick off the processing task. It's "DenyChildAttach" to avoid any surprises if // code happens to create attached tasks, and it's LongRunning because this thread // is likely going to sit around for a while in a wait loop (and the more requests // are concurrently issued to the same agent, the longer the thread will be around). const TaskCreationOptions Options = TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning; _runningWorker = new Task(s => { VerboseTrace("MultiAgent worker starting"); var thisRef = (MultiAgent)s; try { // Do the actual processing thisRef.WorkerLoop(); } catch (Exception exc) { Debug.Fail("Unexpected exception from processing loop: " + exc.ToString()); } finally { VerboseTrace("MultiAgent worker shutting down"); lock (thisRef._incomingRequests) { // Close our wakeup pipe (ignore close errors). // This is done while holding the lock to prevent // subsequent Queue calls to see an improperly configured // set of descriptors. thisRef._wakeupRequestedPipeFd.Dispose(); thisRef._wakeupRequestedPipeFd = null; thisRef._requestWakeupPipeFd.Dispose(); thisRef._requestWakeupPipeFd = null; // In the time between we stopped processing and now, // more requests could have been added. If they were // kick off another processing loop. thisRef._runningWorker = null; if (thisRef._incomingRequests.Count > 0) { thisRef.EnsureWorkerIsRunning(); } } } }, this, CancellationToken.None, Options); _runningWorker.Start(TaskScheduler.Default); // started after _runningWorker field set to avoid race conditions } else // _workerRunning == true { // The worker is already running. If there are already queued requests, we're done. // However, if there aren't any queued requests, Process could be blocked inside of // curl_multi_wait, and we want to make sure it wakes up to see that there additional // requests waiting to be handled. So we write to the wakeup pipe. Debug.Assert(_incomingRequests.Count >= 1, "We just queued a request, so the count should be at least 1"); if (_incomingRequests.Count == 1) { RequestWakeup(); } } }
private void WorkerLoop() { Debug.Assert(!Monitor.IsEntered(_incomingRequests), "No locks should be held while invoking Process"); Debug.Assert(_runningWorker != null && _runningWorker.Id == Task.CurrentId, "This is the worker, so it must be running"); Debug.Assert(_wakeupRequestedPipeFd != null && !_wakeupRequestedPipeFd.IsInvalid, "Should have a valid pipe for wake ups"); // Create the multi handle to use for this round of processing. This one handle will be used // to service all easy requests currently available and all those that come in while // we're processing other requests. Once the work quiesces and there are no more requests // to process, this multi handle will be released as the worker goes away. The next // time a request arrives and a new worker is spun up, a new multi handle will be created. SafeCurlMultiHandle multiHandle = CreateAndConfigureMultiHandle(); // Clear our active operations table. This should already be clear, either because // all previous operations completed without unexpected exception, or in the case of an // unexpected exception we should have cleaned up gracefully anyway. But just in case... Debug.Assert(_activeOperations.Count == 0, "We shouldn't have any active operations when starting processing."); _activeOperations.Clear(); bool endingSuccessfully = false; try { // Continue processing as long as there are any active operations while (true) { // First handle any requests in the incoming requests queue. while (true) { IncomingRequest request; lock (_incomingRequests) { if (_incomingRequests.Count == 0) break; request = _incomingRequests.Dequeue(); } HandleIncomingRequest(multiHandle, request); } // If we have no active operations, we're done. if (_activeOperations.Count == 0) { endingSuccessfully = true; return; } // We have one or more active operations. Run any work that needs to be run. ThrowIfCURLMError(Interop.Http.MultiPerform(multiHandle)); // Complete and remove any requests that have finished being processed. CURLMSG message; IntPtr easyHandle; CURLcode result; while (Interop.Http.MultiInfoRead(multiHandle, out message, out easyHandle, out result)) { Debug.Assert(message == CURLMSG.CURLMSG_DONE, "CURLMSG_DONE is supposed to be the only message type"); if (message == CURLMSG.CURLMSG_DONE) { IntPtr gcHandlePtr; CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(easyHandle, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr); Debug.Assert(getInfoResult == CURLcode.CURLE_OK, "Failed to get info on a completing easy handle"); if (getInfoResult == CURLcode.CURLE_OK) { ActiveRequest completedOperation; bool gotActiveOp = _activeOperations.TryGetValue(gcHandlePtr, out completedOperation); Debug.Assert(gotActiveOp, "Expected to find GCHandle ptr in active operations table"); if (gotActiveOp) { DeactivateActiveRequest(multiHandle, completedOperation.Easy, gcHandlePtr, completedOperation.CancellationRegistration); FinishRequest(completedOperation.Easy, result); } } } } // Wait for more things to do. bool isWakeupRequestedPipeActive; bool isTimeout; ThrowIfCURLMError(Interop.Http.MultiWait(multiHandle, _wakeupRequestedPipeFd, out isWakeupRequestedPipeActive, out isTimeout)); if (isWakeupRequestedPipeActive) { // We woke up (at least in part) because a wake-up was requested. // Read the data out of the pipe to clear it. Debug.Assert(!isTimeout, "should not have timed out if isExtraFileDescriptorActive"); VerboseTrace("curl_multi_wait wake-up notification"); ReadFromWakeupPipeWhenKnownToContainData(); } VerboseTraceIf(isTimeout, "curl_multi_wait timeout"); // PERF NOTE: curl_multi_wait uses poll (assuming it's available), which is O(N) in terms of the number of fds // being waited on. If this ends up being a scalability bottleneck, we can look into using the curl_multi_socket_* // APIs, which would let us switch to using epoll by being notified when sockets file descriptors are added or // removed and configuring the epoll context with EPOLL_CTL_ADD/DEL, which at the expense of a lot of additional // complexity would let us turn the O(N) operation into an O(1) operation. The additional complexity would come // not only in the form of additional callbacks and managing the socket collection, but also in the form of timer // management, which is necessary when using the curl_multi_socket_* APIs and which we avoid by using just // curl_multi_wait/perform. } } finally { // If we got an unexpected exception, something very bad happened. We may have some // operations that we initiated but that weren't completed. Make sure to clean up any // such operations, failing them and releasing their resources. if (_activeOperations.Count > 0) { Debug.Assert(!endingSuccessfully, "We should only have remaining operations if we got an unexpected exception"); foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations) { ActiveRequest failingOperation = pair.Value; IntPtr failingOperationGcHandle = pair.Key; DeactivateActiveRequest(multiHandle, failingOperation.Easy, failingOperationGcHandle, failingOperation.CancellationRegistration); // Complete the operation's task and clean up any of its resources failingOperation.Easy.FailRequest(CreateHttpRequestException()); failingOperation.Easy.Cleanup(); // no active processing remains, so cleanup } // Clear the table. _activeOperations.Clear(); } // Finally, dispose of the multi handle. multiHandle.Dispose(); } }
private void LoadingScreenLoop() { Program.Renderer.PushMatrix(MatrixMode.Projection); Matrix4D.CreateOrthographicOffCenter(0.0f, Program.Renderer.Screen.Width, Program.Renderer.Screen.Height, 0.0f, -1.0f, 1.0f, out Program.Renderer.CurrentProjectionMatrix); Program.Renderer.PushMatrix(MatrixMode.Modelview); Program.Renderer.CurrentViewMatrix = Matrix4D.Identity; while (!Loading.Complete && !Loading.Cancel) { CPreciseTimer.GetElapsedTime(); this.ProcessEvents(); if (this.IsExiting) { Loading.Cancel = true; } double routeProgress = 1.0; for (int i = 0; i < Program.CurrentHost.Plugins.Length; i++) { if (Program.CurrentHost.Plugins[i].Route != null && Program.CurrentHost.Plugins[i].Route.IsLoading) { routeProgress = Program.CurrentHost.Plugins[i].Route.CurrentProgress; break; } } Program.Renderer.Loading.SetLoadingBkg(Program.CurrentRoute.Information.LoadingScreenBackground); Program.Renderer.Loading.DrawLoadingScreen(Fonts.SmallFont, routeProgress, Loading.TrainProgress); Program.currentGameWindow.SwapBuffers(); if (Loading.JobAvailable) { while (jobs.Count > 0) { lock (jobLock) { var currentJob = jobs.Dequeue(); var locker = locks.Dequeue(); currentJob(); lock (locker) { Monitor.Pulse(locker); } } } Loading.JobAvailable = false; } double time = CPreciseTimer.GetElapsedTime(); double wait = 1000.0 / 60.0 - time * 1000 - 50; if (wait > 0) { Thread.Sleep((int)(wait)); } } if (!Loading.Cancel) { Program.Renderer.PopMatrix(MatrixMode.Modelview); Program.Renderer.PopMatrix(MatrixMode.Projection); SetupSimulation(); } else { this.Exit(); } }
public Vector3 MapMT(int i, Vector3 p) { p = tm.MultiplyPoint3x4(p); for (int c = 0; c < curves.Count; c++) { MegaSculptCurve crv = curves[c]; if (crv.enabled) { int ax = (int)crv.axis; if (crv.uselimits) { // Is the point in the box Vector3 bp = p - crv.origin; if (Mathf.Abs(bp.x) < crv.size.x && Mathf.Abs(bp.y) < crv.size.y && Mathf.Abs(bp.z) < crv.size.z) { float alpha = 0.5f + ((bp[ax] / crv.size[ax]) * 0.5f); if (alpha >= 0.0f && alpha <= 1.0f) { Monitor.Enter(resourceLock); float a = crv.curve.Evaluate(alpha) * crv.weight; Monitor.Exit(resourceLock); switch (crv.affectScale) { case MegaAffect.X: p.x += bp.x * (a * crv.sclamount.x); break; case MegaAffect.Y: p.y += bp.y * (a * crv.sclamount.y); break; case MegaAffect.Z: p.z += bp.z * (a * crv.sclamount.z); break; case MegaAffect.XY: p.x += bp.x * (a * crv.sclamount.x); p.y += bp.y * (a * crv.sclamount.y); break; case MegaAffect.XZ: p.x += bp.x * (a * crv.sclamount.x); p.z += bp.z * (a * crv.sclamount.z); break; case MegaAffect.YZ: p.y += bp.y * (a * crv.sclamount.y); p.z += bp.z * (a * crv.sclamount.z); break; case MegaAffect.XYZ: p.x += bp.x * (a * crv.sclamount.x); p.y += bp.y * (a * crv.sclamount.y); p.z += bp.z * (a * crv.sclamount.z); break; } switch (crv.affectOffset) { case MegaAffect.X: p.x += a * crv.offamount.x; break; case MegaAffect.Y: p.y += a * crv.offamount.y; break; case MegaAffect.Z: p.z += a * crv.offamount.z; break; case MegaAffect.XY: p.x += a * crv.offamount.x; p.y += a * crv.offamount.y; break; case MegaAffect.XZ: p.x += a * crv.offamount.x; p.z += a * crv.offamount.z; break; case MegaAffect.YZ: p.y += a * crv.offamount.y; p.z += a * crv.offamount.z; break; case MegaAffect.XYZ: p.x += a * crv.offamount.x; p.y += a * crv.offamount.y; p.z += a * crv.offamount.z; break; } } } } else { float alpha = (p[ax] - bbox.min[ax]) / size[ax]; Monitor.Enter(resourceLock); float a = crv.curve.Evaluate(alpha) * crv.weight; Monitor.Exit(resourceLock); switch (crv.affectScale) { case MegaAffect.X: p.x *= 1.0f + (a * crv.sclamount.y); break; case MegaAffect.Y: p.y *= 1.0f + (a * crv.sclamount.y); break; case MegaAffect.Z: p.z *= 1.0f + (a * crv.sclamount.z); break; case MegaAffect.XY: p.x *= 1.0f + (a * crv.sclamount.y); p.y *= 1.0f + (a * crv.sclamount.y); break; case MegaAffect.XZ: p.x *= 1.0f + (a * crv.sclamount.y); p.z *= 1.0f + (a * crv.sclamount.z); break; case MegaAffect.YZ: p.y *= 1.0f + (a * crv.sclamount.y); p.z *= 1.0f + (a * crv.sclamount.z); break; case MegaAffect.XYZ: p.x *= 1.0f + (a * crv.sclamount.y); p.y *= 1.0f + (a * crv.sclamount.y); p.z *= 1.0f + (a * crv.sclamount.z); break; } switch (crv.affectOffset) { case MegaAffect.X: p.x += a * crv.offamount.x; break; case MegaAffect.Y: p.y += a * crv.offamount.y; break; case MegaAffect.Z: p.z += a * crv.offamount.z; break; case MegaAffect.XY: p.x += a * crv.offamount.x; p.y += a * crv.offamount.y; break; case MegaAffect.XZ: p.x += a * crv.offamount.x; p.z += a * crv.offamount.z; break; case MegaAffect.YZ: p.y += a * crv.offamount.y; p.z += a * crv.offamount.z; break; case MegaAffect.XYZ: p.x += a * crv.offamount.x; p.y += a * crv.offamount.y; p.z += a * crv.offamount.z; break; } } } } return(invtm.MultiplyPoint3x4(p)); }
private void RunLoop() { if (Interlocked.CompareExchange(ref status, WorkerStatus.Started, WorkerStatus.Starting) != WorkerStatus.Starting) { return; } Interlocked.Increment(ref timesStarted); try { lock (msgLock) { //RESET while (Interlocked.CompareExchange(ref status, 0, 0) == WorkerStatus.Started) { Monitor.Wait(msgLock); Log.Debug("msgLock received..."); var op = Interlocked.CompareExchange(ref doOperation, WorkerOperation.NoOp, doOperation); switch (op) { case WorkerOperation.Stop: Log.Debug("Stop Command Issued"); if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started) { Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping); } StopWorkerThreads(); return; //exits case WorkerOperation.Restart: Log.Debug("Restart Command Issued"); if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started) { Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping); } StopWorkerThreads(); StartWorkerThreads(); Interlocked.CompareExchange(ref status, WorkerStatus.Started, WorkerStatus.Stopped); break; //continues } } } } catch (Exception ex) { lastExMsg = ex.Message; Interlocked.Increment(ref noOfErrors); Interlocked.Increment(ref noOfContinuousErrors); if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started) { Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping); } StopWorkerThreads(); if (this.ErrorHandler != null) { this.ErrorHandler(ex); } if (KeepAliveRetryAfterMs != null) { Thread.Sleep(KeepAliveRetryAfterMs.Value); Start(); } } Log.Debug("Exiting RunLoop()..."); }
internal static void ContractAssertMonitorStatus(object syncObj, bool held) { Contract.Requires(syncObj != null, "The monitor object to check must be provided."); Contract.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); }
public void Dispose() { model = default(TModel); Monitor.Exit(syncObject); }
public void Lock() { Monitor.Enter(this); }
public void Dispose() { Monitor.Exit(obj); }
public async Task PubSubGetAllCorrectOrder() { using (var muxer = Create(configuration: TestConfig.Current.RemoteServerAndPort, syncTimeout: 20000)) { var sub = muxer.GetSubscriber(); RedisChannel channel = Me(); const int count = 250; var syncLock = new object(); var data = new List <int>(count); var subChannel = await sub.SubscribeAsync(channel).ForAwait(); await sub.PingAsync().ForAwait(); async Task RunLoop() { while (!subChannel.Completion.IsCompleted) { var work = await subChannel.ReadAsync().ForAwait(); int i = int.Parse(Encoding.UTF8.GetString(work.Message)); lock (data) { data.Add(i); if (data.Count == count) { break; } if ((data.Count % 100) == 99) { Log("Received: " + data.Count.ToString()); } } } lock (syncLock) { Log("PulseAll."); Monitor.PulseAll(syncLock); } } lock (syncLock) { Task.Run(RunLoop); for (int i = 0; i < count; i++) { sub.Publish(channel, i.ToString()); if ((i % 100) == 99) { Log("Published: " + i.ToString()); } } Log("Send loop complete."); if (!Monitor.Wait(syncLock, 20000)) { throw new TimeoutException("Items: " + data.Count); } Log("Unsubscribe."); subChannel.Unsubscribe(); Log("Sub Ping."); sub.Ping(); Log("Database Ping."); muxer.GetDatabase().Ping(); for (int i = 0; i < count; i++) { Assert.Equal(i, data[i]); } } Log("Awaiting completion."); await subChannel.Completion; Log("Completion awaited."); await Assert.ThrowsAsync <ChannelClosedException>(async delegate { var final = await subChannel.ReadAsync().ForAwait(); }).ForAwait(); Log("End of muxer."); } Log("End of test."); }
private static void SendThread(Queue <KeyValuePair <TypeOfSend, byte[]> > p_send_thread_queue, ref bool p_send_thread_queue_flag , ref bool p_send_thread_cancel_flag, ref bool p_receipt_received_flag, object p_send_thread_pulse_object , object p_worker_pulse_object, WorkerReceiveThreadConstruct p_recieve_thread_construct, Socket p_client_socket , ClientWorkerTimer p_worker_timer) { SendWorkerThreadStatus status = SendWorkerThreadStatus.Normal; System.Timers.Timer send_timer = new System.Timers.Timer(); send_timer.Interval = 3000; send_timer.AutoReset = false; Dictionary <int, Thread> all_mini_threads = new Dictionary <int, Thread>(); object all_mini_threads_lock = new object(); bool cancelled = false; int retry_counts = 0; byte[] last_message_sent = new byte[1]; SendThreadResendConstruct resend_construct = new SendThreadResendConstruct(); send_timer.Elapsed += new System.Timers.ElapsedEventHandler((sender, e) => send_timer_Elapsed(sender, e, resend_construct, p_send_thread_pulse_object)); while (true) { lock (p_send_thread_pulse_object) { if (!p_send_thread_cancel_flag && !p_receipt_received_flag && !p_send_thread_queue_flag && !resend_construct.resend_flag) { Monitor.Wait(p_send_thread_pulse_object); } if (p_send_thread_cancel_flag) { status = SendWorkerThreadStatus.End; send_timer.Stop(); cancelled = true; break; } if (p_receipt_received_flag && status == SendWorkerThreadStatus.WaitingForAReceipt) { send_timer.Stop(); retry_counts = 0; status = SendWorkerThreadStatus.Normal; p_receipt_received_flag = false; } if (resend_construct.resend_flag == true && status == SendWorkerThreadStatus.WaitingForAReceipt) { retry_counts++; resend_construct.resend_flag = false; if (retry_counts < 4) { send_timer.Stop(); send_timer.Start(); int sent_data_length = SendData(p_client_socket, last_message_sent); if (sent_data_length > 0) { p_worker_timer.StartAndReset(); } } else { send_timer.Stop(); int mini_thread_id = HelperFunctions.GetGUID(); p_worker_timer.StartAndReset(); status = SendWorkerThreadStatus.Suspended; Thread send_cancel_bytes_to_worker_thead = new Thread(() => SendCancelBytesToWorker(p_worker_pulse_object, p_recieve_thread_construct , all_mini_threads, all_mini_threads_lock, mini_thread_id)); lock (all_mini_threads_lock) { all_mini_threads.Add(mini_thread_id, send_cancel_bytes_to_worker_thead); } send_cancel_bytes_to_worker_thead.Start(); } } if (p_send_thread_queue_flag && (status == SendWorkerThreadStatus.Normal || status == SendWorkerThreadStatus.WaitingForAReceipt)) { if (p_send_thread_queue.Count > 0) { if ((p_send_thread_queue.ElementAt(0).Key == TypeOfSend.WithReceipt && status == SendWorkerThreadStatus.Normal) || (p_send_thread_queue.ElementAt(0).Key == TypeOfSend.WithoutReceipt && (status == SendWorkerThreadStatus.Normal || status == SendWorkerThreadStatus.WaitingForAReceipt))) { KeyValuePair <TypeOfSend, byte[]> send_object = p_send_thread_queue.Dequeue(); if (p_send_thread_queue.Count == 0) { p_send_thread_queue_flag = false; } if (send_object.Key == TypeOfSend.WithReceipt && status == SendWorkerThreadStatus.Normal) { status = SendWorkerThreadStatus.WaitingForAReceipt; last_message_sent = send_object.Value; int sent_data_length = SendData(p_client_socket, send_object.Value); if (sent_data_length > 0) { p_worker_timer.StartAndReset(); } send_timer.Start(); } else if (send_object.Key == TypeOfSend.WithoutReceipt) { SendData(p_client_socket, send_object.Value); p_worker_timer.StartAndReset(); } } } else { p_send_thread_queue_flag = false; } } } } if (cancelled) { send_timer.Stop(); Thread.CurrentThread.Abort(); } }
public void UnLock() { Monitor.Exit(this); }
private static void LoadMachineStores() { Debug.Assert( Monitor.IsEntered(s_machineIntermediateStore), "LoadMachineStores assumes a lock(s_machineIntermediateStore)"); X509Certificate2Collection rootStore = new X509Certificate2Collection(); DirectoryInfo directoryInfo; try { directoryInfo = new DirectoryInfo(Interop.Crypto.GetX509RootStorePath()); } catch (ArgumentException) { // If SSL_CERT_DIR is set to the empty string, or anything else which gives // "The path is not of a legal form", then just call it a day. s_machineRootStore = rootStore; return; } if (!directoryInfo.Exists) { s_machineRootStore = rootStore; return; } HashSet <X509Certificate2> uniqueRootCerts = new HashSet <X509Certificate2>(); HashSet <X509Certificate2> uniqueIntermediateCerts = new HashSet <X509Certificate2>(); foreach (FileInfo file in directoryInfo.EnumerateFiles()) { byte[] bytes; try { bytes = File.ReadAllBytes(file.FullName); } catch (IOException) { // Broken symlink, symlink to a network file share that's timing out, // file was deleted since being enumerated, etc. // // Skip anything that we can't read, we'll just be a bit restrictive // on our trust model, that's all. continue; } catch (UnauthorizedAccessException) { // If, for some reason, one of the files is not world-readable, // and this user doesn't have access to read it, just pretend it // isn't there. continue; } X509Certificate2 cert; try { cert = new X509Certificate2(bytes); } catch (CryptographicException) { // The data was in a format we didn't understand. Maybe it was a text file, // or just a certificate type we don't know how to read. Either way, let's load // what we can. continue; } // The HashSets are just used for uniqueness filters, they do not survive this method. if (StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer)) { if (uniqueRootCerts.Add(cert)) { rootStore.Add(cert); } } else { if (uniqueIntermediateCerts.Add(cert)) { s_machineIntermediateStore.Add(cert); } } } s_machineRootStore = rootStore; }
internal void AcquireLock() { Monitor.Enter(_lockObject); }
FoundLocator(ILocatorPrx? locator) { lock (this) { if (locator == null) { if (_traceLevel > 2) { _lookup.Communicator.Logger.Trace("Lookup", "ignoring locator reply: (null locator)"); } return; } if (_instanceName.Length > 0 && !locator.Identity.Category.Equals(_instanceName)) { if (_traceLevel > 2) { var s = new StringBuilder("ignoring locator reply: instance name doesn't match\n"); s.Append("expected = ").Append(_instanceName); s.Append("received = ").Append(locator.Identity.Category); _lookup.Communicator.Logger.Trace("Lookup", s.ToString()); } return; } // // If we already have a locator assigned, ensure the given locator // has the same identity, otherwise ignore it. // if (_pendingRequests.Count > 0 && _locator != null && !locator.Identity.Category.Equals(_locator.Identity.Category)) { if (!_warned) { _warned = true; // Only warn once locator.Communicator.Logger.Warning( "received Ice locator with different instance name:\n" + "using = `" + _locator.Identity.Category + "'\n" + "received = `" + locator.Identity.Category + "'\n" + "This is typically the case if multiple Ice locators with different " + "instance names are deployed and the property `IceLocatorDiscovery.InstanceName'" + "is not set."); } return; } if (_pending) // No need to continue, we found a locator { _timer.Cancel(this); _pendingRetryCount = 0; _pending = false; } if (_traceLevel > 0) { var s = new StringBuilder("locator lookup succeeded:\nlocator = "); s.Append(locator); if (_instanceName.Length == 0) { s.Append("\ninstance name = ").Append(_instanceName); } _lookup.Communicator.Logger.Trace("Lookup", s.ToString()); } ILocatorPrx? l = null; if (_pendingRequests.Count == 0) { _locators.TryGetValue(locator.Identity.Category, out _locator); } else { l = _locator; } if (l != null) { // We found another locator replica, append its endpoints to the current locator proxy endpoints, // while eliminating duplicates. var newEndpoints = l.Endpoints.Concat(locator.Endpoints).Distinct(); l = l.Clone(endpoints: newEndpoints); } else { l = locator; } if (_pendingRequests.Count == 0) { _locators[locator.Identity.Category] = l; Monitor.Pulse(this); } else { _locator = l; if (_instanceName.Length == 0) { _instanceName = _locator.Identity.Category; // Stick to the first locator } // // Send pending requests if any. // foreach (Request req in _pendingRequests) { _ = req.Invoke(_locator); } _pendingRequests.Clear(); } } }
internal void EnterLock() { Monitor.Enter(InstanceMutationLock); }
public void RunTimerTask() { lock (this) { if (!_pending) { Debug.Assert(_pendingRequests.Count == 0); return; // Request failed } if (_pendingRetryCount > 0) { --_pendingRetryCount; try { if (_traceLevel > 1) { var s = new StringBuilder("retrying locator lookup:\nlookup = "); s.Append(_lookup); s.Append("\nretry count = ").Append(_retryCount); if (_instanceName.Length == 0) { s.Append("\ninstance name = ").Append(_instanceName); } _lookup.Communicator.Logger.Trace("Lookup", s.ToString()); } foreach (KeyValuePair<ILookupPrx, ILookupReplyPrx?> l in _lookups) { _ = FindLocator(l.Key, l.Value!); // Sent multicast request } _timer.Schedule(this, _timeout); return; } catch (Exception) { } _pendingRetryCount = 0; } Debug.Assert(_pendingRetryCount == 0); _pending = false; if (_traceLevel > 0) { var s = new StringBuilder("locator lookup timed out:\nlookup = "); s.Append(_lookup); if (_instanceName.Length == 0) { s.Append("\ninstance name = ").Append(_instanceName); } _lookup.Communicator.Logger.Trace("Lookup", s.ToString()); } if (_pendingRequests.Count == 0) { Monitor.Pulse(this); } else { foreach (Request req in _pendingRequests) { _ = req.Invoke(_voidLocator); } _pendingRequests.Clear(); } _nextRetry = Ice.Time.CurrentMonotonicTimeMillis() + _retryDelay; } }
public void Evaluate(int spreadmax) { if (FInClient.IsConnected) { if (FClient == null && FInClient[0] != null) { FClient = FInClient[0]; FClient.MqttMsgPublishReceived += FClient_MqttMsgPublishReceived; FClient.MqttMsgSubscribed += FClient_MqttMsgSubscribed; FClient.MqttMsgUnsubscribed += FClient_MqttMsgUnsubscribed; FNewSession = true; } if (FClient != null && FInClient[0] == null) { FClient.MqttMsgPublishReceived -= FClient_MqttMsgPublishReceived; FClient.MqttMsgSubscribed -= FClient_MqttMsgSubscribed; FClient.MqttMsgUnsubscribed -= FClient_MqttMsgUnsubscribed; FClient = null; } if (FClient != null && FClient.IsConnected) { if (FInTopic.IsChanged || FNewSession) { HashSet <Tuple <string, QOS> > currentSubscriptions = new HashSet <Tuple <string, QOS> >(); List <Tuple <string, QOS> > newSubscriptions = new List <Tuple <string, QOS> >(); for (int i = 0; i < spreadmax; i++) { if (!string.IsNullOrWhiteSpace(FInTopic[i])) { var tup = new Tuple <string, QOS>(FInTopic[i], FInQoS[i]); currentSubscriptions.Add(tup); if (!FSubscriptions.Remove(tup)) { newSubscriptions.Add(tup); } } } #region unsubscribe try { if (FSubscriptions.Count > 0) { foreach (var tuple in FSubscriptions) { var unsubscribeId = FClient.Unsubscribe(new string[] { tuple.Item1 }); FUnsubscribeStatus.Add(unsubscribeId, tuple); } } FSubscriptions = new HashSet <Tuple <string, QOS> >(currentSubscriptions); } catch (Exception e) { FLogger.Log(e); foreach (var s in currentSubscriptions) { FSubscriptions.Add(s); } } #endregion unsubscribe #region subscribe if (FNewSession) { newSubscriptions.AddRange(FSubscriptions); FNewSession = false; } foreach (var subs in newSubscriptions) { try { var subscribeId = FClient.Subscribe(new string[] { subs.Item1 }, new byte[] { (byte)subs.Item2 }); FSubscribeStatus.Add(subscribeId, subs); } catch { FLogger.Log(LogType.Warning, string.Format("couldn't subscribe to {0} with qos {1}", subs.Item1, subs.Item2)); } } #endregion subscribe } } } bool lockWasTaken = false; try { Monitor.Enter(FQueueLocker, ref lockWasTaken); { FOutTopic.AssignFrom(FPacketQueue.Select(x => x.Topic).ToArray()); FOutMessage.AssignFrom(FPacketQueue.Select(x => UTF8Enc.GetString(x.Message))); FOutQoS.AssignFrom(FPacketQueue.Select(x => (QOS)x.QosLevel)); FOutIsRetained.AssignFrom(FPacketQueue.Select(x => x.Retain)); FOutOnData[0] = FPacketQueue.Count > 0; FPacketQueue.Clear(); if (FMessageStatusQueue.Count > 0) { FOutMessageStatus.AssignFrom(FMessageStatusQueue.ToArray()); FMessageStatusQueue.Clear(); } } } finally { if (lockWasTaken) { Monitor.Exit(FQueueLocker); } } }
public async Task PubSubGetAllCorrectOrder_OnMessage_Async() { using (var muxer = Create(configuration: TestConfig.Current.RemoteServerAndPort, syncTimeout: 20000)) { var sub = muxer.GetSubscriber(); RedisChannel channel = Me(); const int count = 1000; var syncLock = new object(); var data = new List <int>(count); var subChannel = await sub.SubscribeAsync(channel).ForAwait(); subChannel.OnMessage(msg => { int i = int.Parse(Encoding.UTF8.GetString(msg.Message)); bool pulse = false; lock (data) { data.Add(i); if (data.Count == count) { pulse = true; } if ((data.Count % 100) == 99) { Log("Received: " + data.Count.ToString()); } } if (pulse) { lock (syncLock) { Monitor.PulseAll(syncLock); } } return(i % 2 == 0 ? null : Task.CompletedTask); }); await sub.PingAsync().ForAwait(); lock (syncLock) { for (int i = 0; i < count; i++) { sub.Publish(channel, i.ToString(), CommandFlags.FireAndForget); if ((i % 100) == 99) { Log("Published: " + i.ToString()); } } Log("Send loop complete."); if (!Monitor.Wait(syncLock, 20000)) { throw new TimeoutException("Items: " + data.Count); } Log("Unsubscribe."); subChannel.Unsubscribe(); Log("Sub Ping."); sub.Ping(); Log("Database Ping."); muxer.GetDatabase().Ping(); for (int i = 0; i < count; i++) { Assert.Equal(i, data[i]); } } Log("Awaiting completion."); await subChannel.Completion; Log("Completion awaited."); Assert.True(subChannel.Completion.IsCompleted); await Assert.ThrowsAsync <ChannelClosedException>(async delegate { var final = await subChannel.ReadAsync().ForAwait(); }).ForAwait(); Log("End of muxer."); } Log("End of test."); }
public void OverloadSettings() { Monitor.Enter(_watcherSyncObject); var retry = true; var retryCount = 0; while (retry) { try { retryCount++; CreateSettingsIfNotExists(); var overloadSettings = _settingsUtils.GetSettings <PowerLauncherSettings>(PowerLauncherSettings.ModuleName); var openPowerlauncher = ConvertHotkey(overloadSettings.Properties.OpenPowerLauncher); if (_settings.Hotkey != openPowerlauncher) { _settings.Hotkey = openPowerlauncher; } var shell = PluginManager.AllPlugins.Find(pp => pp.Metadata.Name == "Shell"); if (shell != null) { var shellSettings = shell.Plugin as ISettingProvider; shellSettings.UpdateSettings(overloadSettings); } if (_settings.MaxResultsToShow != overloadSettings.Properties.MaximumNumberOfResults) { _settings.MaxResultsToShow = overloadSettings.Properties.MaximumNumberOfResults; } if (_settings.IgnoreHotkeysOnFullscreen != overloadSettings.Properties.IgnoreHotkeysInFullscreen) { _settings.IgnoreHotkeysOnFullscreen = overloadSettings.Properties.IgnoreHotkeysInFullscreen; } var indexer = PluginManager.AllPlugins.Find(p => p.Metadata.Name.Equals("Windows Indexer", StringComparison.OrdinalIgnoreCase)); if (indexer != null) { var indexerSettings = indexer.Plugin as ISettingProvider; indexerSettings.UpdateSettings(overloadSettings); } if (_settings.ClearInputOnLaunch != overloadSettings.Properties.ClearInputOnLaunch) { _settings.ClearInputOnLaunch = overloadSettings.Properties.ClearInputOnLaunch; } if (_settings.Theme != overloadSettings.Properties.Theme) { _settings.Theme = overloadSettings.Properties.Theme; _themeManager.ChangeTheme(_settings.Theme, _settings.Theme == Theme.System); } retry = false; } // the settings application can hold a lock on the settings.json file which will result in a IOException. // This should be changed to properly synch with the settings app instead of retrying. catch (IOException e) { if (retryCount > MaxRetries) { retry = false; Log.Exception($"Failed to Deserialize PowerToys settings, Retrying {e.Message}", e, GetType()); } else { Thread.Sleep(1000); } } catch (JsonException e) { if (retryCount > MaxRetries) { retry = false; Log.Exception($"Failed to Deserialize PowerToys settings, Creating new settings as file could be corrupted {e.Message}", e, GetType()); // Settings.json could possibly be corrupted. To mitigate this we delete the // current file and replace it with a correct json value. _settingsUtils.DeleteSettings(PowerLauncherSettings.ModuleName); CreateSettingsIfNotExists(); ErrorReporting.ShowMessageBox(Properties.Resources.deseralization_error_title, Properties.Resources.deseralization_error_message); } else { Thread.Sleep(1000); } } } Monitor.Exit(_watcherSyncObject); }