本文整理汇总了C#中Semaphore.WaitOne方法的典型用法代码示例。如果您正苦于以下问题:C# Semaphore.WaitOne方法的具体用法?C# Semaphore.WaitOne怎么用?C# Semaphore.WaitOne使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Semaphore
的用法示例。
在下文中一共展示了Semaphore.WaitOne方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
private int Run(int iCount, int mCount, string semName, int iRandom)
{
// Testing createdNew
bool createdNew;
int iRet = -1, count = iCount;
Semaphore sem = null;
if (iRandom > 0)
semName = Common.GenerateUnicodeString(iRandom);
try
{
using(sem = new Semaphore(iCount, mCount, semName, out createdNew))
{
if (iCount > 0)
{
sem.WaitOne();
count--;
}
int iPrev = sem.Release();
if (iPrev == count && createdNew)
iRet = 100;
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected exception thrown: " + ex.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例2: Run
private int Run(int iCount, int mCount)
{
// Testing basic scenario
int iRet = -1;
Semaphore sem = null;
try
{
using (sem = new Semaphore(iCount, mCount))
{
int iPrev = 0, count = iCount;
// Do a wait one if we can
if (iCount > 0)
{
sem.WaitOne();
count--;
}
iPrev = sem.Release();
if (iPrev == count)
iRet = 100;
}
}
catch (Exception ex)
{
Console.WriteLine("FAIL: CtorTest1(" + iCount + "," + mCount + ") - Unexpected exception thrown: " + ex.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例3: CanWaitWithoutBlockingForReleasedCount
public void CanWaitWithoutBlockingForReleasedCount()
{
using (Semaphore s = new Semaphore(0, Int32.MaxValue))
{
for (int counts = 1; counts < 5; counts++)
{
Assert.False(s.WaitOne(0));
if (counts % 2 == 0)
{
for (int i = 0; i < counts; i++)
s.Release();
}
else
{
s.Release(counts);
}
for (int i = 0; i < counts; i++)
{
Assert.True(s.WaitOne(0));
}
Assert.False(s.WaitOne(0));
}
}
}
示例4: CanWaitWithoutBlockingUntilNoCount
public void CanWaitWithoutBlockingUntilNoCount()
{
const int InitialCount = 5;
using (Semaphore s = new Semaphore(InitialCount, InitialCount))
{
for (int i = 0; i < InitialCount; i++)
Assert.True(s.WaitOne(0));
Assert.False(s.WaitOne(0));
}
}
示例5: OpenExisting_SameAsOriginal_Windows
public void OpenExisting_SameAsOriginal_Windows()
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (Semaphore s1 = new Semaphore(0, Int32.MaxValue, name, out createdNew))
{
Assert.True(createdNew);
using (Semaphore s2 = Semaphore.OpenExisting(name))
{
Assert.False(s1.WaitOne(0));
Assert.False(s2.WaitOne(0));
s1.Release();
Assert.True(s2.WaitOne(0));
Assert.False(s2.WaitOne(0));
s2.Release();
Assert.True(s1.WaitOne(0));
Assert.False(s1.WaitOne(0));
}
Semaphore s3;
Assert.True(Semaphore.TryOpenExisting(name, out s3));
using (s3)
{
Assert.False(s1.WaitOne(0));
Assert.False(s3.WaitOne(0));
s1.Release();
Assert.True(s3.WaitOne(0));
Assert.False(s3.WaitOne(0));
s3.Release();
Assert.True(s1.WaitOne(0));
Assert.False(s1.WaitOne(0));
}
}
}
示例6: NamedProducerConsumer
public void NamedProducerConsumer()
{
string name = Guid.NewGuid().ToString("N");
const int NumItems = 5;
var b = new Barrier(2);
Task.WaitAll(
Task.Factory.StartNew(() =>
{
using (var s = new Semaphore(0, int.MaxValue, name))
{
Assert.True(b.SignalAndWait(FailedWaitTimeout));
for (int i = 0; i < NumItems; i++)
Assert.True(s.WaitOne(FailedWaitTimeout));
Assert.False(s.WaitOne(0));
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default),
Task.Factory.StartNew(() =>
{
using (var s = new Semaphore(0, int.MaxValue, name))
{
Assert.True(b.SignalAndWait(FailedWaitTimeout));
for (int i = 0; i < NumItems; i++)
s.Release();
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
}
示例7: AnonymousProducerConsumer
public void AnonymousProducerConsumer()
{
using (Semaphore s = new Semaphore(0, Int32.MaxValue))
{
const int NumItems = 5;
Task.WaitAll(
Task.Factory.StartNew(() =>
{
for (int i = 0; i < NumItems; i++)
Assert.True(s.WaitOne(FailedWaitTimeout));
Assert.False(s.WaitOne(0));
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default),
Task.Factory.StartNew(() =>
{
for (int i = 0; i < NumItems; i++)
s.Release();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
}
}
示例8: Main
static void Main(string[] argv)
{
if (argv.Length < 1)
{
Console.WriteLine("Usage:");
Console.WriteLine("\tUniSynth \"This is a synthetic voice.\"");
Environment.Exit(1);
}
// Just detect various directory layout constellations
if (!Directory.Exists(ROOT_DIR))
ROOT_DIR = "../../../../UniMRCP";
if (!Directory.Exists(ROOT_DIR))
ROOT_DIR = "../../../../unimrcp";
string text = String.Join(" ", argv).Trim();
string outfile = String.Format("{0}/data/{1}", ROOT_DIR, PCM_OUT_FILE);
ushort major, minor, patch;
UniMRCPClient.WrapperVersion(out major, out minor, out patch);
Console.WriteLine("This is a sample C# UniMRCP client synthesizer scenario.");
Console.WriteLine("Wrapper version: {0}.{1}.{2}", major, minor, patch);
Console.WriteLine("Use client configuration from {0}/conf/unimrcpclient.xml", ROOT_DIR);
Console.WriteLine("Use profile {0}", MRCP_PROFILE);
Console.WriteLine("Synthesize text: `{0}'", text);
Console.WriteLine("Write output to file: {0}", outfile);
Console.WriteLine();
Console.WriteLine("Press enter to start the session...");
Console.ReadKey();
UniSynthLogger logger = new UniSynthLogger();
try
{
// Initialize platform first
UniMRCPClient.StaticInitialize(logger, UniMRCPLogPriority.INFO);
}
catch (ApplicationException ex)
{
Console.WriteLine("Unable to initialize platform: " + ex.Message);
Environment.Exit(1);
}
UniMRCPClient client = null;
UniSynthSession sess = null;
UniSynthChannel chan = null;
try
{
// Create and start client in a root dir
client = new UniMRCPClient(ROOT_DIR, true);
// Create a session using MRCP profile MRCP_PROFILE
sess = new UniSynthSession(client, MRCP_PROFILE);
// Create audio termination with capabilities
UniSynthTermination term = new UniSynthTermination(sess, outfile);
term.AddCapability("LPCM", UniMRCPSampleRate.SAMPLE_RATE_8000);
// Semaphore to wait for completion
Semaphore sem = new Semaphore(0, 1);
// Add signaling channel (and start processing in OnAdd method
chan = new UniSynthChannel(sess, term, sem, text);
// Now wait until the processing finishes
sem.WaitOne();
}
catch (ApplicationException ex)
{
err = 1;
Console.WriteLine("An error occured: " + ex.Message);
}
// Ensure correct destruction order (do not let GC decide)
if (chan != null) chan.Dispose();
if (sess != null) sess.Dispose();
if (client != null) client.Dispose();
UniMRCPClient.StaticDeinitialize();
Console.WriteLine("Program finished, memory released. Press enter to exit.");
Console.ReadKey();
Environment.Exit(err);
}
示例9: Main
public static void Main(){
// The value of this variable is set by the semaphore
// constructor. It is true if the named system semaphore was
// created, and false if the named semaphore already existed.
//
bool semaphoreWasCreated;
// Create a Semaphore object that represents the named
// system semaphore "SemaphoreExample". The semaphore has a
// maximum count of five, and an initial count of two. The
// Boolean value that indicates creation of the underlying
// system object is placed in semaphoreWasCreated.
//
Semaphore sem = new Semaphore(2, 5, "SemaphoreExample",
out semaphoreWasCreated);
if (semaphoreWasCreated)
{
// If the named system semaphore was created, its count is
// set to the initial count requested in the constructor.
// In effect, the current thread has entered the semaphore
// three times.
//
Console.WriteLine("Entered the semaphore three times.");
}
else
{
// If the named system semaphore was not created,
// attempt to enter it three times. If another copy of
// this program is already running, only the first two
// requests can be satisfied. The third blocks.
//
sem.WaitOne();
Console.WriteLine("Entered the semaphore once.");
sem.WaitOne();
Console.WriteLine("Entered the semaphore twice.");
sem.WaitOne();
Console.WriteLine("Entered the semaphore three times.");
}
// The thread executing this program has entered the
// semaphore three times. If a second copy of the program
// is run, it will block until this program releases the
// semaphore at least once.
//
Console.WriteLine("Enter the number of times to call Release.");
int n;
if (int.TryParse(Console.ReadLine(), out n))
{
sem.Release(n);
}
int remaining = 3 - n;
if (remaining > 0)
{
Console.WriteLine("Press Enter to release the remaining " +
"count ({0}) and exit the program.", remaining);
Console.ReadLine();
sem.Release(remaining);
}
}
示例10: TestWaitTimeoutWithTimeSpan
public void TestWaitTimeoutWithTimeSpan() {
using(Semaphore semaphore = new Semaphore(1)) {
Assert.IsTrue(semaphore.WaitOne(TimeSpan.FromSeconds(1)));
Assert.IsFalse(semaphore.WaitOne(TimeSpan.FromSeconds(0)));
}
}
示例11: TestWaitTimeout
public void TestWaitTimeout() {
using(Semaphore semaphore = new Semaphore(1)) {
Assert.IsTrue(semaphore.WaitOne(1000));
Assert.IsFalse(semaphore.WaitOne(0));
}
}
示例12: TestThrowOnWaitWithTooLargeTimeSpan
public void TestThrowOnWaitWithTooLargeTimeSpan() {
using(Semaphore semaphore = new Semaphore(1)) {
Assert.Throws<ArgumentOutOfRangeException>(
delegate() {
semaphore.WaitOne(TimeSpan.FromMilliseconds(1L << 32));
}
);
}
}
示例13: PingPong
public void PingPong()
{
// Create names for the two semaphores
string outboundName = Guid.NewGuid().ToString("N");
string inboundName = Guid.NewGuid().ToString("N");
// Create the two semaphores and the other process with which to synchronize
using (var inbound = new Semaphore(1, 1, inboundName))
using (var outbound = new Semaphore(0, 1, outboundName))
using (var remote = RemoteInvoke(PingPong_OtherProcess, outboundName, inboundName))
{
// Repeatedly wait for count in one semaphore and then release count into the other
for (int i = 0; i < 10; i++)
{
Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds));
outbound.Release();
}
}
}
示例14: FuncTest1
public void FuncTest1() {
using (Semaphore sem = new Semaphore(intialCount, maximumCount))
{
sem.WaitOne();
int previousCount = sem.Release();
Console.WriteLine("Previous Count is {0}", previousCount);
if(previousCount != intialCount -1) {
Failure("Previous Count is not correct");
}
else
Success();
try {
sem.Release();
Failure("Expected Exception is not thrown");
}
catch(SemaphoreFullException) {
Success();
}
}
}
示例15: Run
private int Run(int iCount, int mCount, string semName, int iRandom)
{
// Testing createdNew
bool createdNew, createdNew2;
bool bResult = true;
int iRet = -1, count = iCount;
Semaphore sem1 = null, sem2 = null;
if (iRandom > 0)
semName = Common.GenerateUnicodeString(iRandom);
try
{
// Open one, createdNew = true
using (sem1 = new Semaphore(iCount, mCount, semName, out createdNew))
{
if (!createdNew)
bResult = false;
// Open another, createdNew = false
using (sem2 = new Semaphore(iCount, mCount, semName, out createdNew2))
{
if (createdNew2)
bResult = false;
if (iCount > 0)
{
sem2.WaitOne();
count--;
}
int iPrev = sem2.Release();
if (bResult && iPrev == count)
iRet = 100;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected exception thrown: " + ex.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}