public static void ShareMemory() { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(MmfName, 10000)) { Console.WriteLine("Process A started."); bool mutexCreated; var mutex = new Mutex(true, MmfMutex, out mutexCreated); using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { var writer = new BinaryWriter(stream); writer.Write('a'); } mutex.ReleaseMutex(); Console.WriteLine("Please start process B. Once it's done press ENTER."); Console.ReadLine(); mutex.WaitOne(); using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { var reader = new BinaryReader(stream); Console.WriteLine("Process A : {0}", reader.ReadChar()); Console.WriteLine("Process B : {0}", reader.ReadChar()); Console.ReadLine(); } mutex.ReleaseMutex(); } }
public static void BilinearScale(System.Object obj) { ThreadData threadData = (ThreadData)obj; for (var y = threadData.start; y < threadData.end; y++) { int yFloor = (int)Mathf.Floor(y * ratioY); var y1 = yFloor * w; var y2 = (yFloor + 1) * w; var yw = y * w2; for (var x = 0; x < w2; x++) { int xFloor = (int)Mathf.Floor(x * ratioX); var xLerp = x * ratioX - xFloor; newColors[yw + x] = ColorLerpUnclamped(ColorLerpUnclamped(texColors[y1 + xFloor], texColors[y1 + xFloor + 1], xLerp), ColorLerpUnclamped(texColors[y2 + xFloor], texColors[y2 + xFloor + 1], xLerp), y * ratioY - yFloor); } } mutex.WaitOne(); finishCount++; mutex.ReleaseMutex(); }
static void Main(string[] args) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("testmap", 10000)) { bool mutexCreated; Mutex mutex = new Mutex(true, "testmapmutex", out mutexCreated); using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { BinaryWriter writer = new BinaryWriter(stream); Console.Write("Input number =>"); int num = int.Parse(Console.ReadLine()); writer.Write(num); } mutex.ReleaseMutex(); Console.WriteLine("Start Process++ and press ENTER to continue."); Console.ReadLine(); mutex.WaitOne(); using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { BinaryReader reader = new BinaryReader(stream); Console.WriteLine("Process# says: {0}", reader.ReadInt32()); Console.WriteLine("Process++ says: {0}", reader.ReadInt32()); } mutex.ReleaseMutex(); } }
static Mutex SyncLock; //进程互斥锁 #endregion Fields #region Methods static void Main(string[] args) { Console.Title = "实现进程间同步"; try { SyncLock = Mutex.OpenExisting("SyncProcess"); //如果互斥对象已存在则打开该互斥对象 } catch (WaitHandleCannotBeOpenedException) { SyncLock = new Mutex(false, "SyncProcess"); //如果互斥对象不存在则创建一个新的互斥对象 } while (true) { Console.WriteLine("当前进程等待获取互斥对象访问权。"); SyncLock.WaitOne(); Console.WriteLine("获取互斥对象访问权,按Enter键释放互斥对象。\n输入exit键释放互斥对象并退出程序。"); if (Console.ReadLine() == "exit") { SyncLock.ReleaseMutex(); //释放互斥锁 break; } SyncLock.ReleaseMutex(); //释放互斥锁 Console.WriteLine("已释放互斥对象访问权。"); } }
private static void Inc() { for (int i = 0; i < 1000000; i++) { _mutex.WaitOne(); value++; _mutex.ReleaseMutex(); } }
/// <summary> /// Loads any additional static information from the file /// <param name="session">The session this is part of</param> /// </summary> public virtual void LoadStaticData(StockSession session) { var loadMethod = session.Scripts[session].GetStaticMethod("*.Load", File); FileMutex.WaitOne(); File.Seek(LoadAddress, SeekOrigin.Begin); loadMethod(File); FileMutex.ReleaseMutex(); }
static void Main(string[] args) { //args = new string[] { "c" }; bool createNew = true; Mutex mutex = new Mutex(true, "background_changer", out createNew); if (createNew) { if (args.Length > 0) { foreach (var arg in args) { if (arg == CHANGE_BG_COMMAND) { WallHelper.Instance.SetNextWallpaper(); mutex.ReleaseMutex(); return; } } } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); mutex.ReleaseMutex(); } else { Process current = Process.GetCurrentProcess(); Process process = null; foreach (Process proc in Process.GetProcessesByName(current.ProcessName)) { if (proc.Id != current.Id) { process = proc; break; } } if (args.Length > 0) { foreach (var arg in args) { if (arg == CHANGE_BG_COMMAND) { if (process != null) SendMessage(process.MainWindowHandle, WM_MSG, IntPtr.Zero, IntPtr.Zero); else WallHelper.Instance.SetNextWallpaper(); return; } } } if (process != null) SetForegroundWindow(process.MainWindowHandle); } }
public ParameterValuePredictor(ITelemetryClient telemetryClient, IAzContext azContext) { Validation.CheckArgument(telemetryClient, $"{nameof(telemetryClient)} cannot be null."); _telemetryClient = telemetryClient; _azContext = azContext; var fileInfo = new FileInfo(typeof(Settings).Assembly.Location); var directory = fileInfo.DirectoryName; var mappingFilePath = Path.Join(directory, "command_param_to_resource_map.json"); Exception exception = null; try { _commandParamToResourceMap = JsonSerializer.Deserialize <Dictionary <string, Dictionary <string, string> > >(File.ReadAllText(mappingFilePath), JsonUtilities.DefaultSerializerOptions); } catch (Exception e) { // We don't want it to crash the module when the file doesn't exist or when it's mal-formatted. exception = e; } _telemetryClient.OnLoadParameterMap(new ParameterMapTelemetryData(exception)); String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string[] paths = new string[] { path, "Microsoft", "Windows", "PowerShell", "AzPredictor", "paramValueHistory.json" }; _paramValueHistoryFilePath = System.IO.Path.Combine(paths); Directory.CreateDirectory(Path.GetDirectoryName(_paramValueHistoryFilePath)); Task.Run(() => { if (System.IO.File.Exists(_paramValueHistoryFilePath)) { _mutex.WaitOne(); try { var localParameterValues = JsonSerializer.Deserialize <ConcurrentDictionary <string, string> >(File.ReadAllText(_paramValueHistoryFilePath), JsonUtilities.DefaultSerializerOptions); foreach (var v in localParameterValues) { _localParameterValues.AddOrUpdate(v.Key, key => v.Value, (key, oldValue) => oldValue); } } finally { _mutex.ReleaseMutex(); } } }); }
/// <summary>Stops watching the target URL.</summary> public void Stop() { _activated = false; if (_watchTimer == null) { return; } _watchTimer.Dispose(); _watchTimer = null; _mutex.WaitOne(); _mutex.ReleaseMutex(); }
static void Main() { // Add proper exception handling so we can handle plugin exceptions: CreateExceptionHandlingEvents(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); bool succeededToObtainMutex; // Only open one instance of Glue System.Threading.Mutex appMutex = new System.Threading.Mutex(true, Application.ProductName, out succeededToObtainMutex); // Creates a Mutex, if it works, then we can go on and start Glue, if not... if (succeededToObtainMutex) { try { Application.Run(new MainGlueWindow()); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { appMutex.ReleaseMutex(); } } else { //...We come here, and tell the user they already have Glue running. string msg = String.Format("The Program \"{0}\" is already running", Application.ProductName); MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); } }
static void Main() { using (var mutex = new Mutex(false, mutex_id)) { var hasHandle = false; try { try { hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) return; //another instance exist } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired } App app = new App(); app.MainWindow = new MainWindow(); app.Run(); } finally { if (hasHandle) mutex.ReleaseMutex(); } } }
private static void ExecuteLocked(string name, Action action) { bool created; using (var mutex = new Mutex(initiallyOwned: true, name: name, createdNew: out created)) { try { // We need to ensure only one instance of the executable performs the install. All other instances need to wait // for the package to be installed. We'd cap the waiting duration so that other instances aren't waiting indefinitely. if (created) { action(); } else { // if mutex.WaitOne returns false, you don't own the mutex. created = mutex.WaitOne(TimeSpan.FromMinutes(2)); } } finally { // If you don't own the mutex, you can't release it (exception thrown). // cf http://msdn.microsoft.com/en-us/library/system.threading.mutex.releasemutex.aspx if (created) { mutex.ReleaseMutex(); } } } }
// ユーザー・フレンドリなダイアログを表示するメソッド public static void ShowErrorMessage(Exception ex, string extraMessage) { if (MainForm != null) { MainForm.IsApplicationShutDown = true; MainForm.Hide(); MainForm.notification.Visible = false; } string ErrorString = ""; ErrorString += extraMessage + " \n"; ErrorString += "【例外エラー名】\n" + ex.GetType().ToString() + "\n\n"; ErrorString += "【例外が発生したメゾット】\n" + ex.TargetSite + "\n\n"; ErrorString += "【例外が発生したソース】\n" + ex.Source + "\n\n"; ErrorString += "【エラー内容】\n" + ex.Message + "\n\n"; ErrorString += "【スタックトレース】\n" + ex.StackTrace; ExceptionMassage err = new ExceptionMassage(ErrorString, ErrorCount, ex.TargetSite + "") ; //Application.Run(err); #if !DEBUG if (hasHandle) { //ミューテックスを解放する mutex.ReleaseMutex(); } #endif err.Show(); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); bool ownmutex; // Tạo và lấy quyền sở hữu một Mutex có tên là Icon; using (var mutex = new Mutex(true, "AGPF_DADF_IBG", out ownmutex)) { // Nếu ứng dụng sở hữu Mutex, nó có thể tiếp tục thực thi; // nếu không, ứng dụng sẽ thoát. if (ownmutex) { if (CheckConnection()) { Application.Run(new FormMain()); } else { string errorMessage = "Không thể kết nối đến máy chủ. Vui lòng kiểm tra lại đường truyền mạng LAN, hoặc bạn có thể liên hệ với phòng IT để được trợ giúp !"; Application.Run(new FormError(errorMessage)); } //giai phong Mutex; mutex.ReleaseMutex(); } else Application.ExitThread(); } }
static void Main(string[] args) { bool ret; System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out ret); if (ret) { if (IPAddressSelector.Instance().ShowDialog() == DialogResult.OK) { Application.EnableVisualStyles(); System.Windows.Forms.Application.DoEvents(); Application.ApplicationExit += Application_ApplicationExit; Application.ThreadException += Application_ThreadException; Application.ThreadExit += Application_ThreadExit; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; LoginForm form = new LoginForm(); if (form.ShowDialog() == DialogResult.OK) { FlowManager.StartFlowManager(); } mutex.ReleaseMutex(); } } else { MessageBox.Show(null, "有一个和本程序相同的应用程序已经在运行,请不要同时运行多个本程序。\n\n这个程序即将退出。", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); // 提示信息,可以删除。 Application.Exit();//退出程序 } }
public int SendCommand(String command, int val = -1) { String retstr = ""; sPortLock.WaitOne(); try { if (val >= 0) { sPort.WriteLine(":" + command + "," + val.ToString() + "*"); } else { sPort.WriteLine(":" + command + "*"); } while (sPort.BytesToWrite > 0) { } retstr = sPort.ReadTo("*"); } catch (Exception e) { LogMessage("SendCommand exception", e.ToString()); } sPortLock.ReleaseMutex(); return(Int32.Parse(retstr)); }
/// <summary> /// 添加一个消息 /// </summary> public void PushData(Message ci) { mutex.WaitOne(); if (BufferSize > 0 && BufferSize <= cmdq.Count) { Message c = cmdq.Peek() as Message; if (c != null && c.type == MsgQueue.msgtype_Send) { LostCount++; cmdq.Dequeue(); } } cmdq.Enqueue(ci); evt.Set(); mutex.ReleaseMutex(); }
//static void Main() //{ // Application.EnableVisualStyles(); // Application.SetCompatibleTextRenderingDefault(false); // //Thread.Sleep(5000); // Application.Run(new RuChuKuForm()); //} static void Main() { bool noRun = false; Run = new System.Threading.Mutex(true, "HumControl", out noRun); //检测是否已经运行 if (noRun)//未运行 { try { Run.ReleaseMutex(); Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); sysLog.WriteAnyString("---------------------------------------------------------------------------------"); sysLog.WriteDebug("系统开始启动!"); Application.Run(new RuChuKuForm()); } catch { Application.Restart(); } } else//已经运行 { //MessageBox.Show("系统正在运行\r\n请不要重复开启!", "警告!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); //MessageBox.Show("已经有一个实例正在运行!"); //切换到已打开的实例 } }
private static bool DoubleProcess() { bool ok = true; //Mutex名を決める(必ずアプリケーション固有の文字列に変更すること!) string mutexName = "AzureFileWatch"; bool hasHandle = false; //Mutexオブジェクトを作成する System.Threading.Mutex mutex = new System.Threading.Mutex(true, mutexName, out hasHandle); try { //ミューテックスを得られたか調べる if (hasHandle == false) { //得られなかった場合は、すでに起動していると判断して終了 Console.WriteLine("多重起動はできません。"); Console.ReadKey(); ok = false; } } finally { if (hasHandle) { //ミューテックスを解放する mutex.ReleaseMutex(); } mutex.Close(); } return(ok); }
private void Application_Startup(object sender, StartupEventArgs e) { var category = e.Args.Length >= 2 && e.Args[0] == "-c" ? e.Args[1] : null; if (singleton.WaitOne(TimeSpan.Zero, true)) { singleton.ReleaseMutex(); var mainWindow = new MainWindow(category); mainWindow.WindowState = WindowState.Normal; mainWindow.Show(); } else { // send our Win32 message to make the currently running instance // jump on top of all the other windows NativeMethods.PostMessage( (IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); this.Shutdown(); } }
static void Main() { bool isRuned; System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out isRuned); if (isRuned) { try { if (Environment.OSVersion.Version.Major >= 6) { SetProcessDPIAware(); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ServerForm()); mutex.ReleaseMutex(); } catch (Exception e) { //Console.WriteLine("message =" + e.Message); ExceptionLog.getLog().WriteLogFile(e, "LogFile.txt"); } } else { MessageBox.Show(" 程序已启动!\r\n(Program has started)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
static void Main() { Mutex mutex = new System.Threading.Mutex(false, mutexName); bool hasHandle = false; try { //多重起動の抑止 try { hasHandle = mutex.WaitOne(0, false); } catch (AbandonedMutexException) { hasHandle = true; } if (hasHandle == false) { return; } //フック開始 StartHook(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { EndHook(); if (hasHandle) { mutex.ReleaseMutex(); } mutex.Close(); } }
static void Main() { Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); if (IsRight() == false) { return; } bool ret; System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out ret); if (ret) { KillProc("ASNetWks"); KillProc("httpceshi"); Application.EnableVisualStyles(); //这两行实现 XP 可视风格 Application.DoEvents(); //这两行实现 XP 可视风格 Application.Run(new frmLogin()); mutex.ReleaseMutex(); } else { MessageBox.Show(null, "有一个和本程序相同的应用程序正在运行,请先关闭!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); //提示信息,可以删除 Application.Exit();//退出程序 } }
public static void LogLine(string line) { try { logmutex.WaitOne(); } catch (System.Threading.AbandonedMutexException) { } try { System.IO.StreamWriter fstm = System.IO.File.AppendText("do5.txt"); string build = ""; try { System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly(); System.Reflection.AssemblyName an = asm.GetName(); int bn = an.Version.Build; int rv = an.Version.Revision; build = "(do5." + bn.ToString() + "." + rv.ToString() + ") "; } catch { } fstm.WriteLine("[{0} {1}ms] {2}{3}", System.DateTime.Now.ToString(), System.DateTime.Now.Millisecond, build, line); fstm.Close(); } finally { logmutex.ReleaseMutex(); } }
static void Main() { try { mutex = new Mutex(true, Settings.MutexGuid); if (mutex.WaitOne(TimeSpan.Zero, true)) try { RunProgram(); } finally { mutex.ReleaseMutex(); } else Platform.User32.PostMessage( (IntPtr)Platform.PlatformApi.HWND_BROADCAST, Platform.PlatformApi.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); } catch (Exception ex) { HandleError(ex); } finally { if (mutex != null) mutex.Dispose(); } }
public void MultipleQueueManager() { int manifestsProcessed = 0; var manager = new QueueManager(_accessor, new IsolatedStorageQueueStore("test", _accessor)); List<Manifest> manifests = manager.GetManifests().ToList(); foreach (Manifest manifest in manifests) manager.Delete(manifest.Id); const int NUMBER_TO_PROCESS = 20; for (int i = 0; i < NUMBER_TO_PROCESS; i++) manager.Enqueue(CreateSampleError()); var mutex = new Mutex(false, "test"); Parallel.For(0, 5, i => { mutex.WaitOne(); var localManager = new QueueManager(_accessor, new IsolatedStorageQueueStore("test", _accessor)); List<Manifest> localManifests = localManager.GetManifests().ToList(); foreach (Manifest m in localManifests) localManager.Delete(m.Id); Interlocked.Add(ref manifestsProcessed, localManifests.Count); Assert.NotNull(localManifests); mutex.ReleaseMutex(); }); Assert.Equal(NUMBER_TO_PROCESS, manifestsProcessed); foreach (Manifest manifest in manifests) manager.Delete(manifest.Id); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); bool ownmutex; // Tạo và lấy quyền sở hữu một Mutex có tên là Icon; using (var mutex = new Mutex(true, "Shanks_IB02", out ownmutex)) { // Nếu ứng dụng sở hữu Mutex, nó có thể tiếp tục thực thi; // nếu không, ứng dụng sẽ thoát. if (ownmutex) { if (CheckConnection()) { Application.Run(new FormMain()); } else { MessageBox.Show("Connected to database unsuccessful. Please check network, then try again!"); } //giai phong Mutex; mutex.ReleaseMutex(); } else Application.ExitThread(); } }
public static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); bool isNewProcess = false; Mutex mutex = null; try { mutex = new Mutex(true, Application.ProductName, out isNewProcess); if (isNewProcess) { Application.Run(new Snip()); mutex.ReleaseMutex(); } } finally { if (mutex != null) { mutex.Close(); } } // else // { // MessageBox.Show("Another instance of " + Application.ProductName + " is already running.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); // } }
public static void SaveToCache(TwitterResource resource, IEnumerable<TwitterStatus> list) { string fileName = GetCacheName(resource); var serializer = new SharpSerializer(SerializerSettings); Mutex mutex = new Mutex(false, "OCELL_FILE_MUTEX" + fileName); if (mutex.WaitOne(1000)) { try { using (var stream = FileAbstractor.GetFileStream(fileName)) { serializer.Serialize(list.Distinct().OfType<TwitterStatus>().ToList(), stream); } } catch (Exception ex) { Debug.WriteLine(ex); } finally { mutex.ReleaseMutex(); } } mutex.Dispose(); }
static void Main() { //Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); //Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ru-RU"); bool createdNew; var appMutex = new Mutex(true, "MutexDemo.{2B293B02-D2F5-4CE6-8F61-F103E5AC6F51}", out createdNew); try { if (createdNew) { RunNewInstance(); } else { ActivateRunningInstance(); } } finally { if (createdNew) { appMutex.ReleaseMutex(); } } // Вызов GC.KeepAlive гарантирует что переменная appMutex не будет удалена сборщиком мусора // до конца работы функции Main, то есть всего приложения. // Досрочное освобождение мьютекса позволит запустить несколько копий приложения т.к. наше приложение // потеряет его монопольное владение GC.KeepAlive(appMutex); }
public virtual void RemoveDirectoryAccess(string path, string user) { if (DirectoryExists(path) || FileExists(path)) { using (var dirMutex = new System.Threading.Mutex(false, path.Replace('\\', '_'))) { dirMutex.WaitOne(); try { DirectorySecurity security = fileSystem.GetDirectoryAccessSecurity(path); // RemoveAccessRuleAll ignores everything in the ACL but the username var userACL = new FileSystemAccessRule(user, FileSystemRights.ListDirectory, AccessControlType.Allow); security.RemoveAccessRuleAll(userACL); fileSystem.SetDirectoryAccessSecurity(path, security); } finally { dirMutex.ReleaseMutex(); } } } }
// Create all necessary folders before saving the file public static void CreateFolderWhileNotExists(this string filePath) { string finalDirectoryPath = string.Empty; if (!string.IsNullOrEmpty(filePath)) finalDirectoryPath = filePath.Substring(0, filePath.LastIndexOf(@"\")); if (!string.IsNullOrEmpty(finalDirectoryPath) && !Directory.Exists(finalDirectoryPath)) { using (Mutex mutex = new Mutex(false, finalDirectoryPath.GetMutexName())) { mutex.WaitOne(); try { System.IO.Directory.CreateDirectory(finalDirectoryPath); } catch (Exception ex) { throw ex; } finally { mutex.ReleaseMutex(); } } } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Mutex mt = null; try { mt = Mutex.OpenExisting("JustGestures"); string[] args = Environment.GetCommandLineArgs(); } catch (WaitHandleCannotBeOpenedException) { } if (mt == null) { mt = new Mutex(true, "JustGestures"); Application.Run(Form_engine.Instance); GC.KeepAlive(mt); mt.ReleaseMutex(); } else { mt.Close(); MessageBox.Show("Application is already running", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Information); Application.Exit(); } }
// void OnApplicationQuit() { if (m_Mutex != null) { m_Mutex.ReleaseMutex(); } }
public void Run() { while (true) { try { using (var map = MemoryMappedFile.CreateOrOpen(Config.MAPPED_FILE_NAME, Config.BufferSize)) { bool mutexCreated; var mutex = new Mutex(true, "mmfservermutex", out mutexCreated); using (var stream = map.CreateViewStream()) { var writer = new BinaryWriter(stream); var message = GetMessage(); writer.Write(message); Console.WriteLine(message); } mutex.ReleaseMutex(); mutex.WaitOne(); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } }
public static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_ThreadException; bool isFirstInstance; using (Mutex mtx = new Mutex(true, "DevTools", out isFirstInstance)) { if (isFirstInstance) { try { Config.ConfigBase config = new DevToolsConfig(); config = Config.ConfigManager.GetConfig(config.Key); Language.LanguageManager.Code = (config as DevToolsConfig).Language; using (MenuManager menu = new MenuManager()) { menu.Show(); Application.Run(); } } catch (Exception ex) { DTLogger logger = new DTLogger(); logger.Error(ex); } finally { mtx.ReleaseMutex(); } } } }
static void Main(string[] args) { var guidkey = getAssemblyguid(); Console.WriteLine("Assembly guid:{0}", guidkey); var _mutex = new Mutex(true, guidkey); try { if (_mutex.WaitOne(TimeSpan.FromSeconds(0), true)) { _mutex.ReleaseMutex(); Console.WriteLine("start app ok"); } else { Console.WriteLine("exist a running a program"); } } catch (AbandonedMutexException ex) { if (ex.Mutex != null) ex.Mutex.ReleaseMutex(); Console.WriteLine("release ok,and will start a running a program"); //throw; } Console.WriteLine(" program end"); Console.ReadKey(); }
public static IEnumerable<TwitterStatus> GetFromCache(TwitterResource resource) { string fileName = GetCacheName(resource); var serializer = new SharpSerializer(SerializerSettings); Mutex mutex = new Mutex(false, "OCELL_FILE_MUTEX" + fileName); IEnumerable<TwitterStatus> statuses = null; if (mutex.WaitOne(1000)) { try { using (var stream = FileAbstractor.GetFileStream(fileName)) { statuses = serializer.Deserialize(stream) as IEnumerable<TwitterStatus>; } } catch (Exception ex) { Debug.WriteLine(ex); } finally { mutex.ReleaseMutex(); } } mutex.Dispose(); return statuses ?? new List<TwitterStatus>(); }
public void CloseMutex() { bool isNew = false; Mutex closeMutex = new Mutex(true, mutexName, out isNew); if (isNew) { Console.WriteLine("CloseMutex create a new mutex:{0}", mutexName); } else { Console.WriteLine("CloseMutex can't create a new mutex:{0}", mutexName); } closeMutex.WaitOne(); closeMutex.ReleaseMutex(); Console.WriteLine("CloseMutex release mutex."); Thread.Sleep(5000); closeMutex.Close(); Console.WriteLine("Close mutex"); }
public static Mutex AcquireMutex(NodeUri nodeUri, TimeSpan timeout) { Debug.Print("Acquire Mutex for Node URI '{0}'", nodeUri); var mutexName = GetMutexName(nodeUri); Debug.Print("Acquire Mutex name: '{0}'", mutexName); bool mutexCreated; var mutex = new Mutex(false, mutexName, out mutexCreated); Debug.Print("Mutex instance resolved - instance created: {0}", mutexCreated); try { Debug.Print("Try to aquire lock on mutex using timeout {0}", timeout); if (!mutex.WaitOne(timeout)) { throw new TimeoutException(string.Format("Cannot acquire Mutex for URI '{0}' - there is another Node already exists for the same URI", nodeUri)); } Debug.Print("Mutex successfully acquired!"); return mutex; } catch (AbandonedMutexException abandonedMutexException) { Debug.Print("Mutex Abandoned Exception: {0}", abandonedMutexException.Message); mutex.ReleaseMutex(); return AcquireMutex(nodeUri, timeout); } }
static void Main(string[] args) { const int population = 100; //The total population limit and number of initial solutions. const int iterations = 100000; //The total number of iterations. const int elites = 2; //The total number of most optimal solutions to bypass tournament selection at each iteration. const double mutationRate = .7; //The chance of a randomly sized portion of cities being shuffled when producing a child. List <Circuit> individuals = new List <Circuit>(); //Contains the population. Random random = new Random(); //Used for random number generation. Mutex writeAccess = new System.Threading.Mutex(); //Control access to standard output. Task.Run(() => { Console.ReadLine(); writeAccess.WaitOne(); individuals.First().PrintPath(); Environment.Exit(0); }); //Listen for early exit sequence. for (int i = 0; i < population; i++) { individuals.Add(new Circuit().Initialize()); } double latestDistance = individuals.Min(i => i.Distance); for (int i = 0; i < iterations; i++) { individuals = individuals.OrderBy(c => c.Distance).ToList(); //This will allow us to match the best with the worst. #region User Interaction writeAccess.WaitOne(); Console.WriteLine(individuals.First().Distance); writeAccess.ReleaseMutex(); if (individuals.First().Distance != latestDistance) { latestDistance = individuals.First().Distance; Task.Run(() => Console.Beep()); //Beep asynchrnously so you don't slow the program down. } #endregion User Interaction for (int j = 0; j < population; j++) { //Create children from two parents. Note the "*" operator. Circuit child = individuals[j] * individuals[(population - 1) - j]; //Roll for mutation. Randomly select a contiguous range of elements to permute. if (random.NextDouble() < mutationRate) { int upperBound = random.Next(0, child.Path.Count); int lowerBound = random.Next(0, upperBound); child.Path = child.Path.PermutePart(lowerBound, upperBound); } individuals.Add(child); } List <Circuit> nextGeneration = new List <Circuit>(); //Elites bypass and are excluded from selection. nextGeneration.AddRange(individuals.OrderBy(i => i.Distance).Take(elites)); individuals = individuals.OrderBy(i => i.Distance).TakeLast(individuals.Count - elites).ToList(); //Non-elites participate in tournament selection with replacement. for (int j = 0; j < population - elites; j++) { nextGeneration.Add(individuals.RandomChoice() - individuals.RandomChoice()); } individuals = nextGeneration; } individuals = individuals.OrderBy(c => c.Distance).ToList(); Console.WriteLine(individuals.First().Distance); individuals.First().PrintPath(); }
static void Main() { bool bRun = false; log4net.Config.XmlConfigurator.Configure(); System.Threading.Mutex m = new System.Threading.Mutex(true, "EXHAUSTUI", out bRun); if (bRun) { //设置应用程序处理异常方式:ThreadException处理 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理UI线程异常 Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); //处理非UI线程异常 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); BonusSkins.Register(); LoadCulture(); frmMain = new frmMain(); // frmMain.ChangeNotifyIcon(bl == 0 ? false : true); // //} Application.Run(frmMain); } m.ReleaseMutex(); }
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { Stop(); _mutex?.ReleaseMutex(); _mutex?.Dispose(); _mutex = null; }
private static void Main(string[] args) { Mutex mutex = new Mutex(true, AppDomain.CurrentDomain.BaseDirectory.Replace('\\', '_')); if (mutex.WaitOne(100)) { Logger.Instance.WriteMessage("Notifier started."); SkypeNotifier.Instance.StartTimer(); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); Application.Run(new Settings()); SkypeNotifier.Instance.StopTimer(); Logger.Instance.WriteMessage("Notifier halted."); } else { try { Process[] allProcesses = Process.GetProcessesByName("SkypeNotifier"); if (allProcesses.Length > 0) { Win32.SetForegroundWindow(allProcesses[0].MainWindowHandle); } return; } catch { } } mutex.ReleaseMutex(); }
public void WriteMessage(String entry) { // in case we try and log in the event handlers. It's possible // multiple timers will pop at the same time bool requestInitialOwnership = true; bool mutexWasCreated; Mutex m = new Mutex(requestInitialOwnership, "PersonalPictureMgrMutex", out mutexWasCreated); if (!(requestInitialOwnership && mutexWasCreated)) { m.WaitOne(); } using (StreamWriter w = File.AppendText(m_logPath)) { try { DateTime curTime = DateTime.Now; w.Write(curTime.ToString("s")); w.Write(" " + m_methodName + " "); w.WriteLine(entry); } catch (Exception) { } w.Close(); } m.ReleaseMutex(); }
static void Main() { var application_id = "SoundKeyboard 2012"; bool created_new; mMutex = new Mutex(true, application_id, out created_new); if (created_new == false) { MessageBox.Show( "二重起動しようとしました。このアプリケーションは終了します。", application_id, MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); NotifyIcon = new System.Windows.Forms.NotifyIcon(); NotifyIcon.Icon = new System.Drawing.Icon("SoundKeyboard.ico"); NotifyIcon.Visible = true; MainForm = new MainForm(); MainForm.WindowState = FormWindowState.Minimized; MainForm.Show(); /* for initialize, once show. */ MainForm.Hide(); Application.Run(); mMutex.ReleaseMutex(); }
/// <summary> /// Запуск приложения /// </summary> /// <param name="sender">Отправитель</param> /// <param name="args">Аргументы</param> public void OnAppStartup(object sender, StartupEventArgs args) { // Мы должны запускать только один экземпляр приложения if ((AppMutex = Utils.CreateMutex()) != null) { this.Exit += (s, e) => { if (TrayIcon != null) { TrayIcon.Visible = false; } Service.Stop(); AppMutex.ReleaseMutex(); }; bool IsTray = !Utils.HasParameter(args.Args, "-notray"); bool IsAttach = Utils.HasParameter(args.Args, "-attach"); if (IsTray) { BuildIcon(); } if (IsAttach) { Service.Detached += (s, e) => { Utils.CloseApp(); }; } bool IsControl = "2".Equals(Utils.GetRegistryValue(@"HKEY_CURRENT_USER\Keyboard Layout\Toggle\Hotkey", "1")); SetMode(IsControl); Service.Start(IsAttach, IsControl); } else { Utils.CloseApp(); } }
static void Main(string[] args) { bool canCreateNew; //限制单例运行 Mutex mutex = new Mutex(true, "DataTransmission", out canCreateNew); if (canCreateNew) { DateTime dtBeginDateNow = System.DateTime.Now; try { //执行数据传输 dataOperater.Work(); DateTime dtEndDateNow = System.DateTime.Now; TimeSpan ts = dtEndDateNow.Subtract(dtBeginDateNow); Console.Write("开始时间:{0},结束时间{1}, 时差分钟{2},时差秒{3}", dtBeginDateNow.ToString(), dtEndDateNow.ToString(), ts.Minutes.ToString(), ts.Seconds.ToString()); } catch (Exception ex) { throw ex; } finally { mutex.ReleaseMutex(); //释放锁(重要必须) } } else { Console.WriteLine("系统已经有一个实例正在运行之中"); } }
private static void Exit_Clicked(Object sender, EventArgs e) { _TrayIcon.Dispose(); _Mutex.ReleaseMutex(); _WebServer.Stop(); Application.Exit(); }
public static void Main() { Mutex mx = null; bool own = false; try { mx = new Mutex(true, "DisksDB.{5C592533-5E1A-48cb-864C-982359997CA2}", out own); if (true == own) { try { Thread.CurrentThread.Name = "DisksDB main Thread"; Application.EnableVisualStyles(); Application.DoEvents(); Application.Run(new FormMain()); } catch (Exception ex) { Logger.LogException(ex); } } } finally { if ((mx != null) && (true == own)) { mx.ReleaseMutex(); } } }
public AzureIndexInput(AzureDirectory azuredirectory, ICloudBlob blob) : base(blob.Name) { _name = blob.Uri.Segments[blob.Uri.Segments.Length - 1]; _fileMutex = BlobMutexManager.GrabMutex(_name); _fileMutex.WaitOne(); try { _azureDirectory = azuredirectory; _blobContainer = azuredirectory.BlobContainer; _blob = blob; string fileName = _name; StreamOutput fileStream = _azureDirectory.CreateCachedOutputAsStream(fileName); // get the blob _blob.DownloadToStream(fileStream); fileStream.Flush(); Debug.WriteLine("GET {0} RETREIVED {1} bytes", _name, fileStream.Length); fileStream.Close(); // and open it as an input _indexInput = CacheDirectory.openInput(fileName, IOContext.DEFAULT); } finally { _fileMutex.ReleaseMutex(); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //DevExpress.Skins.SkinManager.EnableFormSkins(); //UserLookAndFeel.Default.SetSkinStyle("Office 2013"); CurrentUser=new User(); // Giá trị luận lý cho biết ứng dụng này // có quyền sở hữu Mutex hay không. bool ownmutex; // Tạo và lấy quyền sở hữu một Mutex có tên là Icon; using (var mutex = new Mutex(true, "Icon", out ownmutex)) { // Nếu ứng dụng sở hữu Mutex, nó có thể tiếp tục thực thi; // nếu không, ứng dụng sẽ thoát. if (ownmutex) { Application.Run(new FormLogin()); //giai phong Mutex; mutex.ReleaseMutex(); } else Application.Exit(); } }
private static void LookForRunningProcess(out bool InstanceRunning, out long runningId) { InstanceRunning = false; runningId = 0; Process[] runningProcesses = Process.GetProcesses(); foreach (Process p in runningProcesses) { try { bool ok; m = new System.Threading.Mutex(true, GUI + p.Id.ToString(), out ok); if (!ok) { InstanceRunning = true; runningId = p.Id; break; } else { try { m.ReleaseMutex(); } catch { } } } catch { } } }
public override string GetVideoUrl(VideoInfo video) { string playURL = ""; if (!FeedSync.WaitOne(60000)) { Log.Error("ABCiViewUtil2: Wait for FeedSync Thread failed"); } else { ProgramData programData; if (ProgramDictionary.TryGetValue(video.Other.ToString(), out programData)) { playURL = programData.playURL; } else { //Try and get the Feed Again as it may be out of date Log.Debug("ABCiView2Util: Cannot find episode in TV Feed. Refresh"); new System.Threading.Thread(FeedSyncWorker) { IsBackground = true, Name = "TVFeedDownload" }.Start(iViewTVFeedURL); if (!FeedSync.WaitOne(60000)) { if (ProgramDictionary.TryGetValue(video.Other.ToString(), out programData)) { playURL = programData.playURL; } else { Log.Debug("ABCiView2Util: Cannot find episode in TV Feed after refresh"); } } else { Log.Error("ABCiViewUtil2: Wait for FeedSync Thread failed"); } } FeedSync.ReleaseMutex(); } return(playURL); }
private string GetSqlCeDbFileName(string baseGroupName, string subName, bool createDatabaseIfItDoesNotExist = true) { string fn = Path.Combine(_BasePath, baseGroupName); if (Directory.Exists(fn) == false) { Directory.CreateDirectory(fn); } if (string.IsNullOrEmpty(subName)) { fn = Path.Combine(fn, "_Main.Group.sdf"); } else { fn = Path.Combine(fn, subName + ".sdf"); } if (File.Exists(fn) == false) { //string[] names = this.GetType().Assembly.GetManifestResourceNames(); if (createDatabaseIfItDoesNotExist == false) { return(null); } // Here I need to use a mutex to prevent duplicate creating of the file... this leads to sharing violations... string mutexName = _FileCreateAppId.ToString("D", System.Globalization.CultureInfo.InvariantCulture) + baseGroupName.ToLowerInvariant(); using (var m = new System.Threading.Mutex(false, mutexName)) { m.WaitOne(); try { if (File.Exists(fn) == false) // prüfe hier nochmals, da ich nur hier den Mutex besitze! { using (var db = typeof(AnswersDataEntities).Assembly.GetManifestResourceStream( "CommunityBridge2.WebServiceAnswers.AnswersData.sdf")) { byte[] data = new byte[db.Length]; db.Read(data, 0, data.Length); string fn2 = fn + "_tmp"; using (var f = File.Create(fn2)) { f.Write(data, 0, data.Length); } File.Move(fn2, fn); } } } finally { m.ReleaseMutex(); } } } return(fn); }
private void WriteToFile() { using System.Threading.Mutex mutex = new System.Threading.Mutex(false, "OS-Übergreifender Mutex"); mutex.WaitOne(); File.AppendAllText(_fileName, $"{nameof(Mutex)}: {DateTime.Now:hh:mm:ss:ffff} {Environment.NewLine}"); mutex.ReleaseMutex(); }
public static void ReleaseMutex() { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); mutex = null; } }
public String ReadLine(MutexAction action = MutexAction.NONE) { String cad; if (action == MutexAction.ADQUIRE || action == MutexAction.ATOMIC) { mutex.WaitOne(); } cad = this.input.ReadLine(); if (action == MutexAction.RELAX || action == MutexAction.ATOMIC) { mutex.ReleaseMutex(); } return(cad); }
static void Main(string[] args) { #if !DEBUG Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); // UnhandledExceptionイベント・ハンドラを登録する Thread.GetDomain().UnhandledException += new UnhandledExceptionEventHandler(Application_UnhandledException); #if ADMIN string mutexName = "MisakiEQ(Admin Mode)"; #else string mutexName = "MisakiEQ"; #endif //Mutexオブジェクトを作成する mutex = new System.Threading.Mutex(false, mutexName); try { //ミューテックスの所有権を要求する hasHandle = mutex.WaitOne(0, false); } //.NET Framework 2.0以降の場合 catch (System.Threading.AbandonedMutexException) { //別のアプリケーションがミューテックスを解放しないで終了した時 hasHandle = true; } //ミューテックスを得られたか調べる if (hasHandle == false) { //得られなかった場合は、すでに起動していると判断して終了 MessageBox.Show("MisakiEQは多重起動できません。\nもし表示されない場合はタスクトレイをチェックしてください。", "MisakiEQ", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } #endif Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); for (int i = 0; args.Count() > i; i++) { if (args[i].StartsWith("ErrorFlg=")) { ErrorCount = int.Parse(args[i].Remove(0, 9)); } } MainForm = new MainForm(); Application.Run(MainForm); #if !DEBUG if (hasHandle) { //ミューテックスを解放する mutex.ReleaseMutex(); } #endif }