Mutex 用于在进程中同步的基元
WaitOne() /WaitOne(TimeSpan, Boolean)及若干个重载:请求所有权,该调用会一直阻塞到当前 mutex 收到信号,或直至达到可选的超时间隔,这几个方法都不需要提供锁定对象作为额外参数.
也就是说,mutex.WaitOne会等待1s,如果超时就自动返回false,不在去获取请求mutex的锁。
在万不得已的情况下,不要使用内核模式的锁,因为代价太大。。。其实我们有更多的方式可以替代:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MutexLock
{
class Program
{
static Mutex mutex = new Mutex();
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Thread thread = new Thread(AcquireMutex);
thread.Name = string.Format("Thread{0}", i + 1);
thread.Start();
}
Console.Read();
}
private static void AcquireMutex()
{
// mutex.Waitone() returns boolean
if (!mutex.WaitOne(TimeSpan.FromSeconds(1), false))
{
Console.WriteLine("{0}", Thread.CurrentThread.Name);
return;
}
//mutex.WaitOne();
DoSomething();
mutex.ReleaseMutex();
Console.WriteLine("Mutex released by {0}", Thread.CurrentThread.Name);
}
private static void DoSomething()
{
Thread.Sleep(3000);
}
}
}
第二个dmeo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MutexDemo
{
class Program
{
static Mutex mutex = new Mutex();
static void Main(string[] args)
{
//比如开启5个task
for (int i = 0; i < 5; i++)
{
Task.Factory.StartNew(() =>
{
Run();
});
}
Console.Read();
}
static int nums = 0;
static void Run()
{
for (int i = 0; i < 100; i++)
{
try
{
mutex.WaitOne();
Console.WriteLine(nums++);
mutex.ReleaseMutex();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
}
}
}
}
}