本文整理匯總了C#中System.Threading.Mutex類的典型用法代碼示例。如果您正苦於以下問題:C# Mutex類的具體用法?C# Mutex怎麽用?C# Mutex使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Mutex類屬於System.Threading命名空間,在下文中一共展示了Mutex類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: OnStartup
protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
App.Current.DispatcherUnhandledException += (s, ex) => MessageBox.Show(ex.Exception.ToString());
// Check for running instances of Patchy and kill them
bool isInitialInstance;
Singleton = new Mutex(true, "Patchy:" + SingletonGuid, out isInitialInstance);
if (!isInitialInstance)
KillCurrentInstance();
Singleton.Close();
// Check for permissions
if (!Patchy.UacHelper.IsProcessElevated && !Debugger.IsAttached)
{
var info = new ProcessStartInfo(Assembly.GetEntryAssembly().Location);
info.Verb = "runas";
Process.Start(info);
Application.Current.Shutdown();
return;
}
// Check for .NET 4.0
var value = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", "Install", null);
if (value == null)
{
var result = MessageBox.Show("You must install .NET 4.0 to run Patchy. Would you like to do so now?",
"Error", MessageBoxButton.YesNo, MessageBoxImage.Error);
if (result == MessageBoxResult.Yes)
Process.Start("http://www.microsoft.com/en-us/download/details.aspx?id=17851");
Application.Current.Shutdown();
return;
}
}
示例2: Main
static void Main()
{
mutex = new Mutex(true, Process.GetCurrentProcess().ProcessName, out created);
if (created)
{
//Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//Application.ThreadException += Application_ThreadException;
//AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// As all first run initialization is done in the main project,
// we need to make sure the user does not start a different knot first.
if (CfgFile.Get("FirstRun") != "0")
{
try
{
ProcessStartInfo process = new ProcessStartInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\FreemiumUtilities.exe");
Process.Start(process);
}
catch (Exception)
{
}
Application.Exit();
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
}
}
示例3: Main
static void Main()
{
bool createdMutex;
var updateCheck = new UpdateCheck();
updateCheck.CheckUri = "http://minecraft.etherealwake.com/updates.xml";
updateCheck.Start();
using (var mutex = new Mutex(true, mutexName, out createdMutex)) {
if (createdMutex) {
// Created the mutex, so we are the first instance
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var mainform = new MainForm();
Application.Run(mainform);
GC.KeepAlive(mutex);
} else {
// Not the first instance, so send a signal to wake up the other
try {
var message = NativeMethods.RegisterWindowMessage(mutexName);
if (message != 0) {
NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST,
message, IntPtr.Zero, IntPtr.Zero);
}
} catch {
// We really don't care, we're quitting anyway
}
}
}
}
示例4: SensorForm
public SensorForm(MainForm mainForm)
{
_mf = mainForm;
dispMutex = new Mutex();
InitializeComponent();
waveBoxV.Initialize(10,10,-10);
_lineName.Add((int)DataType.Heading, "艏向角");
_lineName.Add((int)DataType.Pitch, "縱傾");
_lineName.Add((int)DataType.Roll, "橫搖");
_lineName.Add((int)DataType.Pressure, "壓強");
_lineName.Add((int)DataType.Temperature, "溫度");
_lineName.Add((int)DataType.Speed, "航速");
_lineName.Add((int)DataType.Depth, "拖體深度");
_lineName.Add((int)DataType.Altitude, "底深");
MonoColors.Add(Color.Aqua);
MonoColors.Add(Color.Blue);
MonoColors.Add(Color.BlueViolet);
MonoColors.Add(Color.Brown);
MonoColors.Add(Color.BurlyWood);
MonoColors.Add(Color.CadetBlue);
MonoColors.Add(Color.Chartreuse);
MonoColors.Add(Color.Chocolate);
MonoColors.Add(Color.CornflowerBlue);
MonoColors.Add(Color.Crimson);
MonoColors.Add(Color.DeepPink);
waveBoxV.AddLine(_lineName[(int)DataType.Heading], MonoColors[0]);
waveBoxV.AddLine(_lineName[(int)DataType.Pitch], MonoColors[1]);
waveBoxV.AddLine(_lineName[(int)DataType.Roll], MonoColors[2]);
option.bShowHeading = true;
option.bShowPitch = true;
option.bShowRoll = true;
}
示例5: Main
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppPath = (Application.StartupPath.ToLower());
AppPath = AppPath.Replace(@"\bin\debug", @"\").Replace(@"\bin\release", @"\");
AppPath = AppPath.Replace(@"\bin\x86\debug", @"\").Replace(@"\bin\x86\release", @"\");
AppPath = AppPath.Replace(@"\\", @"\");
if (!AppPath.EndsWith(@"\"))
AppPath += @"\";
if (args.Length > 0)
{
ProgramName = args[0];
AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\" + ProgramName +
@"\";
bool firstInstance;
var mutex = new Mutex(false, "iSpyMonitor", out firstInstance);
if (firstInstance)
Application.Run(new Monitor());
mutex.Close();
mutex.Dispose();
}
}
示例6: fmMain_Load
private void fmMain_Load(object sender, EventArgs e)
{
bool r;
AppMutex = new Mutex(true, "AndonSys.AppHelper", out r);
if (!r)
{
MessageBox.Show("係統已運行!",this.Text);
Close();
return;
}
CONFIG.Load();
log = new Log(Application.StartupPath, "AppHelper", Log.DEBUG_LEVEL);
log.Debug("係統運行");
gdApp.AutoGenerateColumns = false;
LoadApp();
tbApp.Show();
timer.Enabled = true;
}
示例7: MutexLock
/// <summary> Locks the provided mutex or throws TimeoutException </summary>
/// <exception cref="System.TimeoutException"> Raises System.TimeoutException if mutex was not obtained. </exception>
public MutexLock(int timeout, Mutex mutex)
{
_wasNew = false;
_mutex = Check.NotNull(mutex);
_disposeMutex = false;
Lock(timeout, ref _wasAbandonded);
}
示例8: Main
static void Main()
{
// Создаём новый мьютекс на время работы программы...
using (Mutex Mtx = new Mutex(false, Properties.Resources.AppName))
{
// Пробуем занять и заблокировать, тем самым проверяя запущена ли ещё одна копия программы или нет...
if (Mtx.WaitOne(0, false))
{
// Включаем визуальные стили...
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Получаем переданные параметры командной строки...
string[] CMDLineA = Environment.GetCommandLineArgs();
// Обрабатываем полученные параметры командной строки...
if (CMDLineA.Length > 2) { if (CMDLineA[1] == "/lang") { try { Thread.CurrentThread.CurrentUICulture = new CultureInfo(CMDLineA[2]); } catch { MessageBox.Show(Properties.Resources.AppUnsupportedLanguage, Properties.Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
// Запускаем главную форму...
Application.Run(new FrmMainW());
}
else
{
// Программа уже запущена. Выводим сообщение об этом...
MessageBox.Show(Properties.Resources.AppAlrLaunched, Properties.Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
// Завершаем работу приложения с кодом 16...
Environment.Exit(16);
}
}
}
示例9: Main
private static void Main()
{
#if DEBUG
//EFlogger.EntityFramework6.EFloggerFor6.Initialize();
#endif
Mutex runOnce = null;
try
{
runOnce = new Mutex(true, "Events_V2_Application_Mutex");
if (runOnce.WaitOne(TimeSpan.Zero))
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += ExceptionHandler.ThreadExceptionHandler;
AppDomain.CurrentDomain.UnhandledException += ExceptionHandler.UnhandledExceptionHandler;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new EventsMainForm());
}
else
{
InfoForm info = new InfoForm()
{
InfoMessage = {Text = @"Приложение уже запущено!"}
};
info.ShowDialog();
}
}
finally
{
if (null != runOnce)
runOnce.Close();
}
}
示例10: Main
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();
}
}
示例11: OnStartup
protected override void OnStartup(StartupEventArgs e)
{
// store mutex result
bool createdNew;
// allow multiple users to run it, but only one per user
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
// create mutex
_instanceMutex = new Mutex(true, @"Global\MercurialForge_Mastery", out createdNew, securitySettings);
// check if conflict
if (!createdNew)
{
MessageBox.Show("Instance of Mastery is already running");
_instanceMutex = null;
Application.Current.Shutdown();
return;
}
base.OnStartup(e);
MainWindow window = new MainWindow();
MainWindowViewModel viewModel = new MainWindowViewModel(window);
window.DataContext = viewModel;
window.Show();
}
示例12: Main
static void Main(string[] args)
{
bool can_execute = true;
try
{
mutex = new System.Threading.Mutex(false, "MONITORMANAGER", out can_execute);
}
catch (Exception ex)
{
_logService.Error("ExistCatch:獲取Mutex時出現異常:" + ex.ToString());
}
if (can_execute)
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args == null || args.Length == 0 || args[0].ToLower() == "true")
{
Application.Run(new MonitorMain(true));
}
else
{
Application.Run(new MonitorMain(false));
}
}
else
{
_logService.Info("MONITORMANAGER already running!");
Debug.WriteLine("MONITORMANAGER already running!");
}
}
示例13: Main
static void Main()
{
bool createdNew; //是否是第一次開啟程序
Mutex mutex = new Mutex(false, "Single", out createdNew);//實例化一個進程互斥變量,標記名稱Single
if (!createdNew) //如果多次開啟了進程
{
Process currentProcess = Process.GetCurrentProcess();//獲取當前進程
foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
{
//通過進程ID和程序路徑來獲取一個已經開啟的進程
if ((process.Id != currentProcess.Id) &&
(Assembly.GetExecutingAssembly().Location == process.MainModule.FileName))
{
//獲取已經開啟的進程的主窗體句柄
IntPtr mainFormHandle = process.MainWindowHandle;
if (mainFormHandle != IntPtr.Zero)
{
ShowWindowAsync(mainFormHandle, 1); //顯示已經開啟的進程窗口
SetForegroundWindow(mainFormHandle); //將已經開啟的進程窗口移動到窗體的最前端
}
}
}
MessageBox.Show("進程已經開啟");
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormSingleProcess());
}
示例14: Main
static void Main()
{
Util.Utils.ReleaseMemory();
using (Mutex mutex = new Mutex(false, "Global\\" + "71981632-A427-497F-AB91-241CD227EC1F"))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (!mutex.WaitOne(0, false))
{
Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
if (oldProcesses.Length > 0)
{
Process oldProcess = oldProcesses[0];
}
MessageBox.Show("Shadowsocks is already running.\n\nFind Shadowsocks icon in your notify tray.");
return;
}
Directory.SetCurrentDirectory(Application.StartupPath);
#if !DEBUG
Logging.OpenLogFile();
#endif
ShadowsocksController controller = new ShadowsocksController();
MenuViewController viewController = new MenuViewController(controller);
controller.Start();
Application.Run();
}
}
示例15: Main
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var c = Process.GetCurrentProcess();
bool instance;
var mutex = new Mutex(true, c.ProcessName + Application.ProductName, out instance);
if (!instance)
{
// Search for instances of this application
var first = false;
foreach (var p in Process.GetProcessesByName(c.ProcessName).Where(p => p.Id != c.Id))
if (!first)
{
first = true;
ShowWindow(p.MainWindowHandle, 5);
SetForegroundWindow(p.MainWindowHandle);
}
else
p.Kill();
}
else
{
Application.Run(new FormMain());
GC.KeepAlive(mutex);
}
}