public void TestThrowOnMoreInitialUsersThanMaximumUsers() { Assert.Throws<ArgumentOutOfRangeException>( delegate() { Semaphore semaphore = new Semaphore(2, 1); semaphore.Close(); } ); }
private RemoteService TryStartProcess(CancellationToken cancellationToken) { Process newProcess = null; int newProcessId = -1; Semaphore semaphore = null; try { string semaphoreName; while (true) { semaphoreName = "HostSemaphore-" + Guid.NewGuid(); bool semaphoreCreated; semaphore = new Semaphore(0, 1, semaphoreName, out semaphoreCreated); if (semaphoreCreated) { break; } semaphore.Close(); cancellationToken.ThrowIfCancellationRequested(); } var remoteServerPort = "HostChannel-" + Guid.NewGuid(); var processInfo = new ProcessStartInfo(HostPath) { Arguments = remoteServerPort + " " + semaphoreName, WorkingDirectory = _initialWorkingDirectory, CreateNoWindow = true, UseShellExecute = false }; newProcess = new Process { StartInfo = processInfo }; newProcess.Start(); cancellationToken.ThrowIfCancellationRequested(); try { newProcessId = newProcess.Id; _childProcessManager.AddProcess(newProcess); } catch { newProcessId = 0; } // sync: while (!semaphore.WaitOne(MillisecondsTimeout)) { if (!newProcess.IsAlive()) { return null; } cancellationToken.ThrowIfCancellationRequested(); } // instantiate remote service: Service newService; try { newService = (Service)Activator.GetObject( typeof(Service), "ipc://" + remoteServerPort + "/" + nameof(Service)); cancellationToken.ThrowIfCancellationRequested(); newService.Initialize(_references.ToArray(), _imports.ToArray(), _nuGetProvider, _initialWorkingDirectory, OnDumped, OnExecutionCompleted); } catch (RemotingException) when (!newProcess.IsAlive()) { return null; } return new RemoteService(newProcess, newProcessId, newService); } catch (OperationCanceledException) { if (newProcess != null) { RemoteService.InitiateTermination(newProcess, newProcessId); } return null; } finally { semaphore?.Close(); } }
static int Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath)); toUpdateLog("started\r\n" + stringArrayToLogString(args, "\t")); if (!s.WaitOne(0)) { Console.WriteLine("semaphore locked to umove.exe; exited"); toUpdateLog("semaphore locked to umove.exe; exited"); return(3); } var umove = false; try { argsString = getArgumentsFromArgArray(args); if (args.Length == 1 && args[0] == "-umove") { var result = umoveRename(); toUpdateLog("-umove"); umove = true; } else { umoveRename(); } if (args.Length == 1 && args[0] == "-v") { AllocConsole(); Console.WriteLine(version); Console.ReadKey(); FreeConsole(); return(0); } createOrParseIni(); var uuPath = downloadUpdate(Directory.GetCurrentDirectory(), opts["updatorDir", ""].Replace("$$$", "update"), "update", version, args); if (!String.IsNullOrEmpty(uuPath)) { try { File.WriteAllText("uup.flag", Path.GetFullPath(uuPath) + "\r\n"); Process.Start("umove.exe", "uup.flag \"vs8.ru updator semaphore\" 50 \"\""); } catch (Exception e) { toUpdateLog(e.Message + "\r\n" + e.StackTrace); } } if (umove) { return(51); } if ( args.Length > 3 || args.Length < 3 || (args.Length == 1 && (args[0] == "-?" || args[0] == "/?" || args[0] == "/help" || args[0].ToLower() == "--help")) ) { AllocConsole(); Console.WriteLine("updatorvs8.exe updateName version path_to_dwnl"); Console.WriteLine("for example: updatorvs8.exe relaxtime 20110929 D:/rtbd/"); Console.WriteLine("warning: umove.exe must be place to same directory updatorvs8.exe"); Console.ReadKey(); FreeConsole(); return(1); } var dirName = args[2]; if (!Directory.Exists(dirName)) { Console.WriteLine(String.Format("update directory '{0}' is not exists", args[1])); return(2); } var updateFlagFile = Path.Combine(new string[] { dirName, "update.flag" }); File.Delete(updateFlagFile); var updatedPath = downloadUpdate(dirName, opts["updateDir", ""].Replace("$$$", args[0]), args[0], args[1], args); var updated = !String.IsNullOrEmpty(updatedPath); if (updated) { File.WriteAllText(updateFlagFile, Path.GetFullPath(updatedPath) + "\r\n"); Console.WriteLine("success"); toUpdateLog("success"); if (args[0] == "relaxtime") { try { var resp = new response(); resp.getFile("http://mc.yandex.ru/watch/15915832", @"http://relaxtime.8vs.ru/success.html?guid=" + opts["updatorGUID"]); } catch (Exception e) { toUpdateLog("success and error: " + e.Message); } } } else { if (updatedPath == null) { Console.WriteLine("failure"); toUpdateLog("failure"); if (args[0] == "relaxtime") { try { var resp = new response(); resp.getFile("http://mc.yandex.ru/watch/15915832", @"http://relaxtime.8vs.ru/failure.html?guid=" + opts["updatorGUID"]); } catch (Exception e) { toUpdateLog("failure and error: " + e.Message); } } } else { Console.WriteLine("neutral"); toUpdateLog("neutral"); if (args[0] == "relaxtime") { try { var resp = new response(); resp.getFile("http://mc.yandex.ru/watch/15915832", @"http://relaxtime.8vs.ru/neutral.html?guid=" + opts["updatorGUID"]); } catch (Exception e) { toUpdateLog("neutral and error: " + e.Message); } } } } toUpdateLog("ended"); var fi = new FileInfo(updatorLogFileName); truncateLog(fi); if (updated) { return(0); } else { return(11); } } finally { s.Release(); s.Close(); } }
public MainWindow() { Settings.LoadFromXmlFile(); CommonManager.Instance.NWMode = Settings.Instance.NWMode; CommonManager.Instance.MM.ReloadWorkData(); CommonManager.Instance.ReloadCustContentColorList(); Settings.Instance.ReloadOtherOptions(); CommonUtil.ApplyStyle(Settings.Instance.NoStyle == 0 ? Settings.Instance.StyleXamlPath : null); SemaphoreSecurity ss = new SemaphoreSecurity(); ss.AddAccessRule(new SemaphoreAccessRule("Everyone", SemaphoreRights.FullControl, AccessControlType.Allow)); semaphore = new Semaphore(int.MaxValue, int.MaxValue, "Global\\EpgTimer_Bon3", out firstInstance, ss); semaphore.WaitOne(0); if (!firstInstance && Settings.Instance.ApplyMultiInstance == false) { ConnectSrv(); DisconnectServer(); semaphore.Release(); semaphore.Close(); semaphore = null; CloseCmd(); return; } InitializeComponent(); #if DEBUG appName += "(debug)"; #endif initExe = true; try { infoWindowViewModel = new InfoWindowViewModel(); // 多重起動時は最小化しない if (firstInstance && Settings.Instance.WakeMin == true) { // Icon化起動すると Windows_Loaded イベントが来ないので // InitializeComponent 後に ConnectCmd しておく。 Dispatcher.BeginInvoke(new Action(() => ConnectCmd(Settings.Instance.NWMode && Settings.Instance.WakeReconnectNW == false) ), DispatcherPriority.Loaded); if (Settings.Instance.ShowTray && Settings.Instance.MinHide) { this.Visibility = Visibility.Hidden; } else { Dispatcher.BeginInvoke(new Action(() => { this.WindowState = System.Windows.WindowState.Minimized; minimizedStarting = true; })); } } //ウインドウ位置の復元 if (Settings.Instance.MainWndTop != -100) { this.Top = Settings.Instance.MainWndTop; } if (Settings.Instance.MainWndLeft != -100) { this.Left = Settings.Instance.MainWndLeft; } if (Settings.Instance.MainWndWidth != -100) { this.Width = Settings.Instance.MainWndWidth; } if (Settings.Instance.MainWndHeight != -100) { this.Height = Settings.Instance.MainWndHeight; } this.WindowState = Settings.Instance.LastWindowState; //上のボタン Action<string, Action> ButtonGen = (key, handler) => { Button btn = new Button(); btn.MinWidth = 75; btn.Margin = new Thickness(2, 2, 2, 5); btn.Click += (sender, e) => handler(); btn.Content = key; buttonList.Add(key, btn); }; ButtonGen("設定", OpenSettingDialog); ButtonGen("再接続", OpenConnectDialog); ButtonGen("再接続(前回)", () => ConnectCmd()); ButtonGen("検索", OpenSearchDialog); ButtonGen("スタンバイ", () => SuspendCmd(1)); ButtonGen("休止", () => SuspendCmd(2)); ButtonGen("終了", CloseCmd); ButtonGen("EPG取得", EpgCapCmd); ButtonGen("EPG再読み込み", EpgReloadCmd); ButtonGen("NetworkTV終了", NwTVEndCmd); ButtonGen("情報通知ログ", OpenNotifyLogDialog); ButtonGen("予約簡易表示", () => ShowInfoWindow()); ButtonGen("カスタム1", () => CustumCmd(1)); ButtonGen("カスタム2", () => CustumCmd(2)); ButtonGen("カスタム3", () => CustumCmd(3)); //検索ボタンは他と共通でショートカット割り振られているので、その部分はコマンド側で処理する。 this.CommandBindings.Add(new CommandBinding(EpgCmds.Search, (sender, e) => CommonButtons_Click("検索"))); mBinds.AddInputCommand(EpgCmds.Search); SetSearchButtonTooltip(buttonList["検索"]); StatusbarReset();//ステータスバーリセット if(Settings.Instance.InfoWindowEnabled) { ShowInfoWindow(); } //タスクトレイの表示 taskTray = new TaskTrayClass(this); if (CommonManager.Instance.NWMode == true && Settings.Instance.ChkSrvRegistTCP == true) { taskTray.Icon = TaskIconSpec.TaskIconGray; } else { taskTray.Icon = TaskIconSpec.TaskIconBlue; } taskTray.ContextMenuClick += (sender, e) => CommonButtons_Click(sender as string); ResetMainView(); //初期タブ選択 switch (Settings.Instance.StartTab) { //case CtxmCode.ReserveView: // this.tabItem_reserve.IsSelected = true; // break; case CtxmCode.TunerReserveView: this.tabItem_tunerReserve.IsSelected = true; break; case CtxmCode.RecInfoView: this.tabItem_recinfo.IsSelected = true; break; case CtxmCode.EpgAutoAddView: this.tabItem_AutoAdd.IsSelected = true; // this.autoAddView.tabItem_epgAutoAdd.IsSelected = true; break; case CtxmCode.ManualAutoAddView: this.tabItem_AutoAdd.IsSelected = true; this.autoAddView.tabItem_manualAutoAdd.IsSelected = true; break; case CtxmCode.EpgView: this.tabItem_epg.IsSelected = true; break; } } catch (Exception ex) { ExceptionLogger.Log(ex); MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
public MainWindow() { Settings.LoadFromXmlFile(); CommonManager.Instance.NWMode = Settings.Instance.NWMode; CommonManager.Instance.MM.ReloadWorkData(); CommonManager.Instance.ReloadCustContentColorList(); if (Settings.Instance.NoStyle == 0) { if (System.IO.File.Exists(System.Reflection.Assembly.GetEntryAssembly().Location + ".rd.xaml")) { //ResourceDictionaryを定義したファイルがあるので本体にマージする try { App.Current.Resources.MergedDictionaries.Add( (ResourceDictionary)System.Windows.Markup.XamlReader.Load( System.Xml.XmlReader.Create(System.Reflection.Assembly.GetEntryAssembly().Location + ".rd.xaml"))); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } else { //既定のテーマ(Aero)をマージする App.Current.Resources.MergedDictionaries.Add( Application.LoadComponent(new Uri("/PresentationFramework.Aero, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35;component/themes/aero.normalcolor.xaml", UriKind.Relative)) as ResourceDictionary ); } } SemaphoreSecurity ss = new SemaphoreSecurity(); ss.AddAccessRule(new SemaphoreAccessRule("Everyone", SemaphoreRights.FullControl, AccessControlType.Allow)); semaphore = new Semaphore(int.MaxValue, int.MaxValue, "Global\\EpgTimer_Bon2", out firstInstance, ss); semaphore.WaitOne(0); if (!firstInstance) { CheckCmdLine(); if (Settings.Instance.ApplyMultiInstance == false) { semaphore.Release(); semaphore.Close(); semaphore = null; CloseCmd(); return; } } InitializeComponent(); initExe = true; try { // 多重起動時は最小化しない if (firstInstance && Settings.Instance.WakeMin == true) { // Icon化起動すると Windows_Loaded イベントが来ないので // InitializeComponent 後に ConnectCmd しておく。 if (Settings.Instance.NWMode == false || Settings.Instance.WakeReconnectNW == true) { ConnectCmd(false); } if (Settings.Instance.ShowTray && Settings.Instance.MinHide) { this.Visibility = Visibility.Hidden; } else { Dispatcher.BeginInvoke(new Action(() => { this.WindowState = System.Windows.WindowState.Minimized; })); } } //ウインドウ位置の復元 if (Settings.Instance.MainWndTop != -100) { this.Top = Settings.Instance.MainWndTop; } if (Settings.Instance.MainWndLeft != -100) { this.Left = Settings.Instance.MainWndLeft; } if (Settings.Instance.MainWndWidth != -100) { this.Width = Settings.Instance.MainWndWidth; } if (Settings.Instance.MainWndHeight != -100) { this.Height = Settings.Instance.MainWndHeight; } this.WindowState = Settings.Instance.LastWindowState; //上のボタン Action<string, RoutedEventHandler> ButtonGen = (key, handler) => { Button btn = new Button(); btn.MinWidth = 75; btn.Margin = new Thickness(2, 2, 2, 5); if (handler != null) btn.Click += new RoutedEventHandler(handler); btn.Content = key; buttonList.Add(key, btn); }; ButtonGen("設定", settingButton_Click); ButtonGen("検索", null); ButtonGen("終了", closeButton_Click); ButtonGen("スタンバイ", standbyButton_Click); ButtonGen("休止", suspendButton_Click); ButtonGen("EPG取得", epgCapButton_Click); ButtonGen("EPG再読み込み", epgReloadButton_Click); ButtonGen("カスタム1", custum1Button_Click); ButtonGen("カスタム2", custum2Button_Click); ButtonGen("NetworkTV終了", nwTVEndButton_Click); ButtonGen("情報通知ログ", logViewButton_Click); ButtonGen("再接続", connectButton_Click); ButtonGen("予約簡易表示", showInfoWindowButton_Click); //検索ボタンは他と共通でショートカット割り振られているので、コマンド側で処理する。 this.CommandBindings.Add(new CommandBinding(EpgCmds.Search, searchButton_Click)); mBinds.SetCommandToButton(buttonList["検索"], EpgCmds.Search); RefreshButton(); ResetButtonView(); //タスクトレイの表示 taskTray = new TaskTrayClass(this); taskTray.Icon = Properties.Resources.TaskIconBlue; taskTray.Visible = Settings.Instance.ShowTray; taskTray.ContextMenuClick += new EventHandler(taskTray_ContextMenuClick); taskTray.Text = GetTaskTrayReserveInfoText(); ResetTaskMenu(); CheckCmdLine(); // 設定から情報を読み取るので設定をロードした後作る infoWindowViewModel = new InfoWindowViewModel(); if(Settings.Instance.InfoWindowEnabled) { ShowInfoWindow(); } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
static int Main(string[] args) { AppDomain CurrentDomain = AppDomain.CurrentDomain; CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); #if DEBUG DbgLog.dbg.Disabled = false; DbgLog.dbg.setLogRegime(null, -1); DbgLog.dbg.setLogRegime(DbgLog.ERROR, 0); DbgLog.dbg.setLogRegime(DbgLog.MESSAGE, 0); #else DbgLog.dbg.Disabled = false; DbgLog.dbg.setLogRegime(null, -1); DbgLog.dbg.setLogRegime(DbgLog.ERROR, 0); #endif if (args.Length == 1 && args[0] == "-v") { AllocConsole(); Console.WriteLine(version); Console.ReadKey(); FreeConsole(); DbgLog.allLogsDispose(); return(0); } Directory.SetCurrentDirectory(Application.StartupPath); // анинсталляция if (args.Length > 0) { if (args[0] == "uninstall") { Uninstall(false); } else { AllocConsole(); Console.WriteLine("no correct parameters:\r\n\t uninstall - doing uninstallation"); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); FreeConsole(); } DbgLog.allLogsDispose(); return(0); } if (!m.WaitOne(10)) { // Не выводим сообщение, чтобы освободить exe-файл для обновления как можно быстрее // MessageBox.Show("Невозможно запустить две программы 'relax time black display' одновременно", "Недопустимо", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); ToLogFile("semaphore locked - program exited"); DbgLog.allLogsDispose(); return(3); } // toLogFileMessage("semaphore is green - program started"); try { DbgLog.dbg.messageToLog("", "semaphore is green - program started"); /*if (File.Exists("update.flag")) * { * toLogFile("update.flag exists - exit program"); * Form1.updateProcessStart(); * return 31; * } */ /* * try * { * var fs = new FileSecurity(Path.GetFullPath(Application.StartupPath), AccessControlSections.Access); * fs.SetAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, FileSystemRights.CreateFiles | FileSystemRights.CreateDirectories | FileSystemRights.ChangePermissions | FileSystemRights.AppendData | FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.ListDirectory | FileSystemRights.Modify | FileSystemRights.ReadAndExecute | FileSystemRights.Write, AccessControlType.Allow)); * } * catch (Exception ex) * { * MessageBox.Show(ex.Message); * }*/ //File.SetAccessControl(Path.GetDirectoryName(Application.StartupPath), fs); // setUninstall(); TruncateLog(new FileInfo(Application.StartupPath + errorLogFileName)); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); mainForm = new Form1(); Application.Run(mainForm); } finally { m.Release(); m.Close(); } DbgLog.allLogsDispose(); return(0); }
public void Dispose() { _lock.Release(); _lock.Close(); }
private void continueBtn_Click(object sender, EventArgs e) { CloseApp ca = (CloseApp)this.stepPanel.Controls[0]; ca.continueBtn.Enabled = false; ca.richTextBox1.Text = "Closing Program..."; semaphore = new Semaphore(0, 1); Thread thread = new Thread(ThreadFun); thread.Start(); semaphore.WaitOne(); semaphore.Close(); ca.continueBtn.Click -= new EventHandler(continueBtn_Click); UnInstalling ui = new UnInstalling(); this.stepPanel.Controls.RemoveAt(0); this.stepPanel.Controls.Add(ui); ca.Dispose(); uninstalling = true; backgroundWorker1.RunWorkerAsync(); }
private void ReproduceByParallelThreads() { #region Parallel Reproduct Code Thread[] th = new Thread[countCPUCore]; // Create a semaphore that can satisfy up to three // concurrent requests. Use an initial count of zero, // so that the entire semaphore count is initially // owned by the main program thread. // Semaphore sem = new Semaphore(countCPUCore, countCPUCore); bool[] isAlive = new bool[countCPUCore]; bool[] isCompleted = new bool[countCPUCore]; int length = (Npop - N_keep) / countCPUCore; int divideReminder = (Npop - N_keep) % countCPUCore; for (int proc = 0; proc < th.Length; proc++) { ThreadToken tt = new ThreadToken(proc, length + ((proc == countCPUCore - 1) ? divideReminder : 0), N_keep + (proc * length)); th[proc] = new Thread(new ParameterizedThreadStart((x) => { // Entered sem.WaitOne(); isAlive[((ThreadToken)x).No] = true; // work ... PReproduction(((ThreadToken)x).startIndex, ((ThreadToken)x).length, ((ThreadToken)x).rand); // We have finished our job, so release the semaphore isCompleted[((ThreadToken)x).No] = true; sem.Release(); })); setThreadPriority(th[proc]); th[proc].Start(tt); } startloop: foreach (bool alive in isAlive) // wait parent starter for start all children. if (!alive) goto startloop; endLoop: sem.WaitOne(); foreach (bool complete in isCompleted) // wait parent to interrupt for finishes all of children jobs. if (!complete) goto endLoop; // Continue Parent Work sem.Close(); #endregion }