本文整理汇总了C#中System.Threading.Semaphore类的典型用法代码示例。如果您正苦于以下问题:C# Semaphore类的具体用法?C# Semaphore怎么用?C# Semaphore使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Semaphore类属于System.Threading命名空间,在下文中一共展示了Semaphore类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CoalescedAnnounce
public static CoalescedAnnounceResponse CoalescedAnnounce(this Tracker tracker, params IAnnounceRequest[] announceList)
{
InternalAnnounceResponseCollection annnounceResponses = new InternalAnnounceResponseCollection();
Semaphore requestSemaphore = new Semaphore(TrackerSettings.MaxConcurrency, TrackerSettings.MaxConcurrency);
IAsyncResult[] results = new IAsyncResult[announceList.Length];
for(int i = 0; i < announceList.Length; i++)
results[i] = tracker.BeginAnnounce(announceList[i], new AsyncCallback((result) => requestSemaphore.Release()), announceList[i].InfoHash);
foreach (IAsyncResult result in results)
{
IAnnounceResponse response = null;
try
{
response = tracker.EndAnnounce(result);
}
catch { }
if(response != null)
annnounceResponses.Add((InfoHash)result.AsyncState, new InternalAnnounceResponse(
response.Interval,
response.Complete,
response.Incomplete,
response.Peers)
);
}
return new CoalescedAnnounceResponse(annnounceResponses);
}
示例2: ThreadPool
private ThreadPool(int queueSize, int threadNum)
{
#if UNITY_WEBPLAYER
threadNum = 1;
#else
if (threadNum == 0)
{
threadNum = SystemInfo.processorCount;
}
#endif
m_threadPool = new Thread[threadNum];
m_taskQueue = new TaskInfo[queueSize];
m_nPutPointer = 0;
m_nGetPointer = 0;
m_numTasks = 0;
m_putNotification = new AutoResetEvent(false);
m_getNotification = new AutoResetEvent(false);
#if !UNITY_WEBPLAYER
if (1 < threadNum)
{
m_semaphore = new Semaphore(0, queueSize);
for (int i = 0; i < threadNum; ++i)
{
m_threadPool[i] = new Thread(ThreadFunc);
m_threadPool[i].Start();
}
}
else
#endif
{
m_threadPool[0] = new Thread(SingleThreadFunc);
m_threadPool[0].Start();
}
}
示例3: DisplayHandler
public DisplayHandler(iMonWrapperApi imon)
{
if (imon == null)
{
throw new ArgumentNullException("imon");
}
this.imon = imon;
this.imon.StateChanged += stateChanged;
this.queue = new List<Text>();
this.icons = new Dictionary<iMonLcdIcons, bool>(Enum.GetValues(typeof(iMonLcdIcons)).Length);
foreach (iMonLcdIcons icon in Enum.GetValues(typeof(iMonLcdIcons)))
{
this.icons.Add(icon, false);
}
this.discRotation = new System.Timers.Timer();
this.discRotation.AutoReset = true;
this.discRotation.Interval = 300;
this.discRotation.Elapsed += discRotationElapsed;
this.WorkerReportsProgress = false;
this.WorkerSupportsCancellation = true;
this.semReady = new Semaphore(0, 1);
this.semWork = new Semaphore(0, 1);
}
示例4: SoundEffects
//Constructor
public SoundEffects(ref AxWindowsMediaPlayer axMedia, ref Semaphore soundSem, ref Semaphore mediaSem, ref Boolean stop)
{
//Assign variables
soundSemaphore = soundSem;
mediaSemaphore = mediaSem;
media = axMedia;
media.settings.setMode("loop", false);
stopped = stop;
//Determine if sound folder already exists
if (!Directory.Exists(currentDirectory))
{
try
{
Directory.CreateDirectory(currentDirectory); //if not, create it
} catch { }
}
//Get the length of every sound file
MaxTurboLength = GetSoundLength(currentDirectory + "\\MaxTurbo.wav") + 1000;
Start1Length = GetSoundLength(currentDirectory + "\\Start1.wav") + 1000;
Start2Length = GetSoundLength(currentDirectory + "\\Start2.wav") + 1000;
LoopLength = GetSoundLength(currentDirectory + "\\Loop.wav") + 1000;
StopLength = GetSoundLength(currentDirectory + "\\Stop.wav") + 1000;
sound = new System.Media.SoundPlayer(currentDirectory + "\\MaxTurbo.wav");
}
示例5: Runner
public Runner()
{
Console.Write("TestDvDeviceCs - starting\n");
DeviceBasic device = new DeviceBasic();
iDeviceList = new List<CpDevice>();
CpDeviceList.ChangeHandler added = new CpDeviceList.ChangeHandler(DeviceAdded);
CpDeviceList.ChangeHandler removed = new CpDeviceList.ChangeHandler(DeviceRemoved);
CpDeviceListUpnpServiceType list = new CpDeviceListUpnpServiceType("openhome.org", "TestBasic", 1, added, removed);
Semaphore sem = new Semaphore(0, 1);
sem.WaitOne(1000);
Debug.Assert(iDeviceList.Count == 1);
TestBasicCp cp = new TestBasicCp(iDeviceList[0]);
cp.TestActions();
cp.TestSubscriptions();
list.Dispose();
lock (this)
{
for (int i = 0; i < iDeviceList.Count; i++)
{
iDeviceList[i].RemoveRef();
}
}
device.Dispose();
Console.Write("TestDvDeviceCs - completed\n");
}
示例6: Fork
public Fork(int index)
{
_index = index;
_forkLock = new Semaphore(1, 1);
_isTaken = false;
_isForEat = true;
}
示例7: Execute
public override bool Execute()
{
if (File.Exists(PropsFile) && File.Exists(TargetsFile))
{
return true;
}
string semaphoreName = PropsFile.ToUpper().GetHashCode().ToString("X");
bool releaseSemaphore;
using (Semaphore semaphore = new Semaphore(0, 1, semaphoreName, out releaseSemaphore))
{
try
{
if (!releaseSemaphore)
{
releaseSemaphore = semaphore.WaitOne(TimeSpan.FromMinutes(5));
return releaseSemaphore;
}
return GenerateBuildPackageImportFile();
}
finally
{
if (releaseSemaphore)
{
semaphore.Release();
}
}
}
}
示例8: Gateway
public Gateway()
{
gateClosed = false;
gateSemaphore = new Semaphore(1, 1);
numberOfGateClosers = 0;
gateControlSemaphore = new Semaphore(1, 1);
}
示例9: Main
public static void Main()
{
const int count = 4;
_desk = new Semaphore(0, count - 1);
var forks = new List<Fork>(count);
var philosophers = new List<Philosopher>(count);
for (var i = 0; i < count; i++)
{
forks.Add(new Fork {Number = i});
}
philosophers.Add(new Philosopher(_desk, count - 1) { LeftFork = forks[count - 1], RightFork = forks[0], Number = 0, HungerLevel = 0 });
for (var i = 1; i < count; i++)
{
philosophers.Add(new Philosopher(_desk, count - 1) { LeftFork = forks[i - 1], RightFork = forks[i], Number = i, HungerLevel = count - 1 });
}
var tasks = new Task[count];
for (var i = 0; i < count; i++)
{
var idx = i;
tasks[idx] = new Task(() => philosophers[idx].Start());
}
_desk.Release(count - 1);
Parallel.ForEach(tasks, t => t.Start());
Console.ReadKey();
}
示例10: ProcessBaseImplThreads
/*Object Parent;
public ProcessBaseImplThreads(Object Parent)
{
this.Parent = Parent;
}*/
public void Init(RunDelegate Delegate)
{
//Console.WriteLine("Init(" + Parent + ")");
if (mainThread == null)
{
SemaphoreGlobal = new Semaphore(1, 1);
SemaphoreGlobal.WaitOne();
mainThread = Thread.CurrentThread;
//mainMutex.WaitOne();
}
Semaphore = new Semaphore(1, 1);
Semaphore.WaitOne();
currentThread = new Thread(delegate()
{
Semaphore.WaitOne();
//currentThread.Interrupt();
Delegate();
});
currentThread.Start();
//Mutex.WaitOne();
}
示例11: waitFullSemaphore
/// <summary>
/// Analogiczna dla WaitHandle.WaitAll - wymuś uzyskanie kilku dostępów na semaforze. Po uzyskaniu tej liczby dostępów, zwolnij je
/// wszystkie. Funkcja do tego czasu blokuje.
/// </summary>
/// <param name="semaphore">Semafor</param>
/// <param name="waitCount">Ile użyć na semaforze</param>
public static void waitFullSemaphore(Semaphore semaphore, int waitCount)
{
for (int i = 0; i < waitCount; i++)
semaphore.WaitOne();
semaphore.Release(waitCount);
}
示例12: MultualExclusiongUsingSemaphore
public static void MultualExclusiongUsingSemaphore() {
count = 0;
Semaphore writeSem = new Semaphore(1, 1);
answer.Clear();
Random executionLengthRand = new Random();
Thread[] threadArray = new Thread[1000];
for (int i = 0; i < 1000; i++)
{
threadArray[i] = new Thread(
() =>
{
int temp = -1;
executionLengthRand.Next(697);
writeSem.WaitOne();
count = count + 1;
temp = count;
executionLengthRand.Next(1937);
writeSem.Release();
answer.Push(temp);
}
);
threadArray[i].Start();
}
foreach (var t in threadArray)
{
t.Join();
}
foreach (var item in answer.Reverse())
{
Console.WriteLine(item);
}
}
示例13: LocalPool
public LocalPool(
int numCommandThread = 4,
int numMatLabThread = 4,
int numCADThread = 2)
{
ts = new CancellationTokenSource();
ct = ts.Token;
tf = new TaskFactory(
ct,
TaskCreationOptions.LongRunning,
TaskContinuationOptions.None,
null);
int numAllThread = numCommandThread + numMatLabThread + numCADThread;
// do not use more threads than cores
numAllThread = numAllThread < Environment.ProcessorCount ?
numAllThread :
Environment.ProcessorCount;
NumAllThread = numAllThread;
NumCommandThread = numCommandThread;
NumMatLabThread = numMatLabThread;
NumCADThread = numCADThread;
SemAll = new Semaphore(numAllThread, numAllThread);
SemJob = new Dictionary<Job.TypeEnum, Semaphore>();
SemJob.Add(Job.TypeEnum.Command, new Semaphore(numCommandThread, numCommandThread));
SemJob.Add(Job.TypeEnum.Matlab, new Semaphore(numMatLabThread, numMatLabThread));
SemJob.Add(Job.TypeEnum.CAD, new Semaphore(numCADThread, numCADThread));
}
示例14: SemaphoreObject
public SemaphoreObject(string name, int maxCount, int freeCount, IntPtr formHandle, RichThread thread)
: base(name, false, formHandle, thread)
{
this.maxCount = maxCount;
this.freeCount = freeCount;
this.waitHandle = new Semaphore(freeCount, maxCount);
}
示例15: WidokMiniatur
/// <summary>
/// Konstruktor bezparametryczny
/// </summary>
public WidokMiniatur()
{
WyswietloneZdjecia = new List<IZdjecie>();
WszystkieZdjecia = new List<IZdjecie>();
katalogi = new Katalog[0];
tagi = new List<long>();
LargeImageList = new ImageList();
LargeImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
LargeImageList.Tag = "100%";
LargeImageList.TransparentColor = System.Drawing.Color.Transparent;
LargeImageList.ImageSize = new Size(Config.RozmiarMiniatury + 2, Config.RozmiarMiniatury + 2);
//Activate double buffering
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
katalog = Properties.Resources.katalog;
katalog_do_gory = Properties.Resources.katalog_do_gory;
Edycja = false;
sem = new Semaphore(0, 1);
sem.Release();
}