本文整理汇总了C#中Mutex类的典型用法代码示例。如果您正苦于以下问题:C# Mutex类的具体用法?C# Mutex怎么用?C# Mutex使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Mutex类属于命名空间,在下文中一共展示了Mutex类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
private int Run()
{
int iRet = -1;
string sName = Common.GetUniqueName();
// Basic test, not owned
using(mut = new Mutex(false, sName))
{
Thread t = new Thread(new ThreadStart(OwnMutex));
t.Start();
mre.WaitOne();
try
{
Mutex mut1 = Mutex.OpenExisting(sName);
mut1.WaitOne();
mut1.ReleaseMutex();
iRet = 100;
}
catch (Exception ex)
{
Console.WriteLine("Unexpected exception thrown: " +
ex.ToString());
}
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例2: Main
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
var zzz = new z();
bool createdNew;
#if DEBUG || RELEASE_TEST
#else
Mutex instance = new Mutex(true, zzz.GetType().ToString(), out createdNew);
if (!createdNew)
{
MessageBox.Show("不能多开");
return;
}
#endif
try
{
Application.Run(zzz);
//Application.Run(new ShipForm());
}
catch (Exception e)
{
write_dump(e.ToString());
}
//var f = new CommandForm();
//Application.Run(f);
}
示例3: OpenExisting_Windows
public void OpenExisting_Windows()
{
string name = Guid.NewGuid().ToString("N");
Mutex resultHandle;
Assert.False(Mutex.TryOpenExisting(name, out resultHandle));
using (Mutex m1 = new Mutex(false, name))
{
using (Mutex m2 = Mutex.OpenExisting(name))
{
Assert.True(m1.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m1.ReleaseMutex();
Assert.True(m2.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m2.ReleaseMutex();
}
Assert.True(Mutex.TryOpenExisting(name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
示例4: Awake
void Awake()
{
SetupWebCamTexture();
InitializeAruco();
mutex_ = new Mutex();
thread_ = new Thread(() => {
try {
for (;;) {
Thread.Sleep(0);
if (!isArucoUpdated_) {
mutex_.WaitOne();
var num = aruco_detect(aruco_, false);
GetMarkers(num);
mutex_.ReleaseMutex();
isArucoUpdated_ = true;
}
}
} catch (Exception e) {
if (!(e is ThreadAbortException)) {
Debug.LogError("Unexpected Death: " + e.ToString());
}
}
});
thread_.Start();
}
示例5: Run
private int Run()
{
int iRet = -1;
string sName = Common.GetUniqueName();
// open a Mutex that has been abandoned
mut = new Mutex(false, sName);
Thread th = new Thread(new ParameterizedThreadStart(AbandonMutex));
th.Start(mut);
mre.WaitOne();
try
{
Mutex mut1 = Mutex.OpenExisting(sName);
mut1.WaitOne();
}
catch (AbandonedMutexException)
{
//Expected
iRet = 100;
}
catch (Exception e)
{
Console.WriteLine("Caught unexpected exception: " +
e.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例6: Run
private int Run()
{
int iRet = -1;
string sName = Common.GetUniqueName();
// Open an abandoned mutex
using (mut = new Mutex(false, sName))
{
Thread t = new Thread(new ThreadStart(AbandonMutex));
t.Start();
t.Join();
try
{
Mutex mut1 = Mutex.OpenExisting(sName);
iRet = 100;
}
catch (Exception ex)
{
Console.WriteLine("Unexpected exception thrown: " +
ex.ToString());
}
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例7: Run
private int Run()
{
int iRet = -1;
string sName = Common.GetUniqueName();
// open a semaphore with the same name as a mutex
Mutex mu = new Mutex(false, sName);
try
{
using (Semaphore sem = Semaphore.OpenExisting(sName))
{
}
}
catch (WaitHandleCannotBeOpenedException)
{
//Expected
iRet = 100;
}
catch (Exception e)
{
Console.WriteLine("Caught unexpected exception: " +
e.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例8: GetDefaultUsername
#pragma warning restore 0414
private string GetDefaultUsername()
{
var count = 0;
while (true)
{
var name = string.Format("{0}_{1}_{2}", Application.companyName, Application.productName, count);
bool created;
m_nameMutex = new Mutex(true, name, out created);
if (created)
{
break;
}
count++;
}
var username = Environment.UserName;
if (count > 0)
{
username = string.Format("{0} ({1})", username, count);
}
return username;
}
示例9: OpenExisting
public void OpenExisting()
{
const string Name = "MutexTestsOpenExisting";
Mutex resultHandle;
Assert.False(Mutex.TryOpenExisting(Name, out resultHandle));
using (Mutex m1 = new Mutex(false, Name))
{
using (Mutex m2 = Mutex.OpenExisting(Name))
{
Assert.True(m1.WaitOne());
Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m1.ReleaseMutex();
Assert.True(m2.WaitOne());
Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m2.ReleaseMutex();
}
Assert.True(Mutex.TryOpenExisting(Name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
示例10: Run
private int Run()
{
int iRet = -1;
Console.WriteLine("Abandon same named mutex");
// Create array with the same name
wh = new Mutex[2];
string sName = Common.GetUniqueName();
wh[0] = new Mutex(false, sName);
wh[1] = new Mutex(false, sName);
Thread t = new Thread(new
ParameterizedThreadStart(this.AbandonMutexPos));
t.Start(0);
t.Join();
try
{
Console.WriteLine("Waiting...");
int i = WaitHandle.WaitAny(wh, 5000);
Console.WriteLine("WaitAny did not throw an " +
"exception, i = " + i);
}
catch(AbandonedMutexException)
{
// Expected
iRet = 100;
}
catch(Exception e)
{
Console.WriteLine("Unexpected exception thrown: " +
e.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例11: Main
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Application.Run(new FormLineCanon());
// 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());
Application.Run(new FormLogin());
//giai phong Mutex;
mutex.ReleaseMutex();
}
else
Application.Exit();
}
}
示例12: Main
public static int Main(String[] args)
{
Console.WriteLine("MutexSample.cs ...");
gM1 = new Mutex(true,"MyMutex");
gM2 = new Mutex(true);
Console.WriteLine(" - Main Owns gM1 and gM2");
AutoResetEvent[] evs = new AutoResetEvent[4];
evs[0] = Event1;
evs[1] = Event2;
evs[2] = Event3;
evs[3] = Event4;
MutexSample tm = new MutexSample( );
Thread t1 = new Thread(new ThreadStart(tm.t1Start));
Thread t2 = new Thread(new ThreadStart(tm.t2Start));
Thread t3 = new Thread(new ThreadStart(tm.t3Start));
Thread t4 = new Thread(new ThreadStart(tm.t4Start));
t1.Start( );
t2.Start( );
t3.Start( );
t4.Start( );
Thread.Sleep(2000);
Console.WriteLine(" - Main releases gM1");
gM1.ReleaseMutex( );
Thread.Sleep(1000);
Console.WriteLine(" - Main releases gM2");
gM2.ReleaseMutex( );
WaitHandle.WaitAll(evs);
Console.WriteLine("... MutexSample.cs");
return 0;
}
示例13: ReuseMutexThread
public void ReuseMutexThread()
{
Console.WriteLine("Waiting to reuse mutex");
manualEvent.WaitOne();
bool exists;
Mutex mutex = new Mutex(true, mutexName, out exists);
if (exists)
{
Console.WriteLine("Error, created new mutex!");
success = 97;
}
else
{
mutex.WaitOne();
}
try
{
Console.WriteLine("Mutex reused {0}", exists);
mutex.ReleaseMutex();
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception: {0}", e);
success = 98;
}
exitEvent.Set();
}
示例14: Main
static void Main()
{
bool isFirstInstance;
var mutex = new Mutex(true, "VolumeWheelEx", out isFirstInstance);
if(isFirstInstance) {
try {
Hook.SetHook();
var exit = false;
while(!exit) { try { exit = WinAPI.GetMessage(IntPtr.Zero, IntPtr.Zero, 0, 0) > 0; } catch(NullReferenceException) { /* Don't worry, GetMessage can sometimes returns NULL. */ } };
Hook.UnHook();
} catch(Exception e) {
//LOG file directly on desktop
System.IO.File.AppendAllText(Environment.GetEnvironmentVariable("userprofile") + "\\Desktop\\VolumeWheelEx.log", "[" + DateTime.Now.ToString() + "]\n" + e.Source + " -> " + e.ToString() + "\n" + e.StackTrace + "\n\n");
} finally {
mutex.ReleaseMutex();
}
} else {
try {
var thisProc = Process.GetCurrentProcess();
var prcs = Process.GetProcessesByName(thisProc.ProcessName);
for(int i = 0; i < prcs.Length; i++) {
if(prcs[i].Id != thisProc.Id) {
WinAPI.PostThreadMessage((uint)prcs[i].Threads[0].Id, WinAPI.WM_QUIT, UIntPtr.Zero, IntPtr.Zero);
}
}
} catch { }
}
}
示例15: PosTest1
public bool PosTest1()
{
bool retVal = true;
Thread thread = null;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Construct a new Mutex instance with initiallyOwned set to true (ensure that the thread owns the mutex)");
using(m_Mutex = new Mutex(true))
{
try
{
do
{
if (null == m_Mutex)
{
TestLibrary.TestFramework.LogError("001", "Can not construct a new Mutex intance with initiallyOwned set to true.");
retVal = false;
break;
}
// Ensure initial owner of the mutex is current thread
// Create another thread to change value of m_SharedResource
thread = new Thread(new ThreadStart(ThreadProc));
thread.Start();
// Sleep 1 second to wait the thread get started
Thread.Sleep(c_DEFAULT_SLEEP_TIME);
if (m_SharedResource != c_DEFAULT_INT_VALUE)
{
TestLibrary.TestFramework.LogError("002", "Call Mutex(true) does not set current thread to be the owner of the mutex.");
retVal = false;
}
m_Mutex.ReleaseMutex();
} while (false); // do
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
if (null != thread)
{
// Wait until all threads are terminated
thread.Join();
}
// Reset the value of m_SharedResource for further usage
m_SharedResource = c_DEFAULT_INT_VALUE;
}
}
return retVal;
}