本文整理汇总了C#中System.Threading.Mutex.Mutex构造函数的典型用法代码示例。如果您正苦于以下问题:C# Mutex构造函数的具体用法?C# Mutex怎么用?C# Mutex使用的例子?那么恭喜您, 这里精选的构造函数代码示例或许可以为您提供帮助。您也可以进一步了解该构造函数所在类System.Threading.Mutex
的用法示例。
在下文中一共展示了Mutex构造函数的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Mutex
// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.
using System;
using System.Threading;
class Test
{
// Create a new Mutex. The creating thread does not own the
// Mutex.
private static Mutex mut = new Mutex();
private const int numIterations = 1;
private const int numThreads = 3;
static void Main()
{
// Create the threads that will use the protected resource.
for(int i = 0; i < numThreads; i++)
{
Thread myThread = new Thread(new ThreadStart(MyThreadProc));
myThread.Name = String.Format("Thread{0}", i + 1);
myThread.Start();
}
// The main thread exits, but the application continues to
// run until all foreground threads have exited.
}
private static void MyThreadProc()
{
for(int i = 0; i < numIterations; i++)
{
UseResource();
}
}
// This method represents a resource that must be synchronized
// so that only one thread at a time can enter.
private static void UseResource()
{
// Wait until it is safe to enter.
mut.WaitOne();
Console.WriteLine("{0} has entered the protected area",
Thread.CurrentThread.Name);
// Place code to access non-reentrant resources here.
// Simulate some work.
Thread.Sleep(500);
Console.WriteLine("{0} is leaving the protected area\r\n",
Thread.CurrentThread.Name);
// Release the Mutex.
mut.ReleaseMutex();
}
}
示例2: Mutex
//引入命名空间
using System;
using System.Threading;
class Test
{
// Create a new Mutex. The creating thread owns the Mutex.
private static Mutex mut = new Mutex(true);
private const int numIterations = 1;
private const int numThreads = 3;
static void Main()
{
// Create the threads that will use the protected resource.
for(int i = 0; i < numThreads; i++)
{
Thread myThread = new Thread(new ThreadStart(MyThreadProc));
myThread.Name = String.Format("Thread{0}", i + 1);
myThread.Start();
}
// Wait one second before allowing other threads to
// acquire the Mutex.
Console.WriteLine("Creating thread owns the Mutex.");
Thread.Sleep(1000);
Console.WriteLine("Creating thread releases the Mutex.\r\n");
mut.ReleaseMutex();
}
private static void MyThreadProc()
{
for(int i = 0; i < numIterations; i++)
{
UseResource();
}
}
// This method represents a resource that must be synchronized
// so that only one thread at a time can enter.
private static void UseResource()
{
// Wait until it is safe to enter.
mut.WaitOne();
Console.WriteLine("{0} has entered the protected area",
Thread.CurrentThread.Name);
// Place code to access non-reentrant resources here.
// Simulate some work.
Thread.Sleep(500);
Console.WriteLine("{0} is leaving the protected area\r\n",
Thread.CurrentThread.Name);
// Release the Mutex.
mut.ReleaseMutex();
}
}
输出:
Creating thread owns the Mutex. Creating thread releases the Mutex. Thread1 has entered the protected area Thread1 is leaving the protected area Thread2 has entered the protected area Thread2 is leaving the protected area Thread3 has entered the protected area Thread3 is leaving the protected area
示例3: Main
//引入命名空间
using System;
using System.Threading;
public class Test
{
public static void Main()
{
// Create the named mutex. Only one system object named
// "MyMutex" can exist; the local Mutex object represents
// this system object, regardless of which process or thread
// caused "MyMutex" to be created.
Mutex m = new Mutex(false, "MyMutex");
// Try to gain control of the named mutex. If the mutex is
// controlled by another thread, wait for it to be released.
Console.WriteLine("Waiting for the Mutex.");
m.WaitOne();
// Keep control of the mutex until the user presses
// ENTER.
Console.WriteLine("This application owns the mutex. " +
"Press ENTER to release the mutex and exit.");
Console.ReadLine();
m.ReleaseMutex();
}
}
示例4: Main
// This example shows how a named mutex is used to signal between
// processes or threads.
// Run this program from two (or more) command windows. Each process
// creates a Mutex object that represents the named mutex "MyMutex".
// The named mutex is a system object whose lifetime is bounded by the
// lifetimes of the Mutex objects that represent it. The named mutex
// is created when the first process creates its local Mutex; in this
// example, the named mutex is owned by the first process. The named
// mutex is destroyed when all the Mutex objects that represent it
// have been released.
// The second process (and any subsequent process) waits for earlier
// processes to release the named mutex.
using System;
using System.Threading;
public class Test
{
public static void Main()
{
// Set this variable to false if you do not want to request
// initial ownership of the named mutex.
bool requestInitialOwnership = true;
bool mutexWasCreated;
// Request initial ownership of the named mutex by passing
// true for the first parameter. Only one system object named
// "MyMutex" can exist; the local Mutex object represents
// this system object. If "MyMutex" is created by this call,
// then mutexWasCreated contains true; otherwise, it contains
// false.
Mutex m = new Mutex(requestInitialOwnership,
"MyMutex",
out mutexWasCreated);
// This thread owns the mutex only if it both requested
// initial ownership and created the named mutex. Otherwise,
// it can request the named mutex by calling WaitOne.
if (!(requestInitialOwnership && mutexWasCreated))
{
Console.WriteLine("Waiting for the named mutex.");
m.WaitOne();
}
// Once the process has gained control of the named mutex,
// hold onto it until the user presses ENTER.
Console.WriteLine("This process owns the named mutex. " +
"Press ENTER to release the mutex and exit.");
Console.ReadLine();
// Call ReleaseMutex to allow other threads to gain control
// of the named mutex. If you keep a reference to the local
// Mutex, you can call WaitOne to request control of the
// named mutex.
m.ReleaseMutex();
}
}
示例5: Main
//引入命名空间
using System;
using System.Threading;
using System.Security.AccessControl;
internal class Example
{
internal static void Main()
{
const string mutexName = "MutexExample4";
Mutex m = null;
bool doesNotExist = false;
bool unauthorized = false;
// The value of this variable is set by the mutex
// constructor. It is true if the named system mutex was
// created, and false if the named mutex already existed.
//
bool mutexWasCreated = false;
// Attempt to open the named mutex.
try
{
// Open the mutex with (MutexRights.Synchronize |
// MutexRights.Modify), to enter and release the
// named mutex.
//
m = Mutex.OpenExisting(mutexName);
}
catch(WaitHandleCannotBeOpenedException)
{
Console.WriteLine("Mutex does not exist.");
doesNotExist = true;
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine("Unauthorized access: {0}", ex.Message);
unauthorized = true;
}
// There are three cases: (1) The mutex does not exist.
// (2) The mutex exists, but the current user doesn't
// have access. (3) The mutex exists and the user has
// access.
//
if (doesNotExist)
{
// The mutex does not exist, so create it.
// Create an access control list (ACL) that denies the
// current user the right to enter or release the
// mutex, but allows the right to read and change
// security information for the mutex.
//
string user = Environment.UserDomainName + "\\"
+ Environment.UserName;
MutexSecurity mSec = new MutexSecurity();
MutexAccessRule rule = new MutexAccessRule(user,
MutexRights.Synchronize | MutexRights.Modify,
AccessControlType.Deny);
mSec.AddAccessRule(rule);
rule = new MutexAccessRule(user,
MutexRights.ReadPermissions | MutexRights.ChangePermissions,
AccessControlType.Allow);
mSec.AddAccessRule(rule);
// Create a Mutex object that represents the system
// mutex named by the constant 'mutexName', with
// initial ownership for this thread, and with the
// specified security access. The Boolean value that
// indicates creation of the underlying system object
// is placed in mutexWasCreated.
//
m = new Mutex(true, mutexName, out mutexWasCreated, mSec);
// If the named system mutex was created, it can be
// used by the current instance of this program, even
// though the current user is denied access. The current
// program owns the mutex. Otherwise, exit the program.
//
if (mutexWasCreated)
{
Console.WriteLine("Created the mutex.");
}
else
{
Console.WriteLine("Unable to create the mutex.");
return;
}
}
else if (unauthorized)
{
// Open the mutex to read and change the access control
// security. The access control security defined above
// allows the current user to do this.
//
try
{
m = Mutex.OpenExisting(mutexName,
MutexRights.ReadPermissions | MutexRights.ChangePermissions);
// Get the current ACL. This requires
// MutexRights.ReadPermissions.
MutexSecurity mSec = m.GetAccessControl();
string user = Environment.UserDomainName + "\\"
+ Environment.UserName;
// First, the rule that denied the current user
// the right to enter and release the mutex must
// be removed.
MutexAccessRule rule = new MutexAccessRule(user,
MutexRights.Synchronize | MutexRights.Modify,
AccessControlType.Deny);
mSec.RemoveAccessRule(rule);
// Now grant the user the correct rights.
//
rule = new MutexAccessRule(user,
MutexRights.Synchronize | MutexRights.Modify,
AccessControlType.Allow);
mSec.AddAccessRule(rule);
// Update the ACL. This requires
// MutexRights.ChangePermissions.
m.SetAccessControl(mSec);
Console.WriteLine("Updated mutex security.");
// Open the mutex with (MutexRights.Synchronize
// | MutexRights.Modify), the rights required to
// enter and release the mutex.
//
m = Mutex.OpenExisting(mutexName);
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine("Unable to change permissions: {0}",
ex.Message);
return;
}
}
// If this program created the mutex, it already owns
// the mutex.
//
if (!mutexWasCreated)
{
// Enter the mutex, and hold it until the program
// exits.
//
try
{
Console.WriteLine("Wait for the mutex.");
m.WaitOne();
Console.WriteLine("Entered the mutex.");
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine("Unauthorized access: {0}", ex.Message);
}
}
Console.WriteLine("Press the Enter key to exit.");
Console.ReadLine();
m.ReleaseMutex();
m.Dispose();
}
}