本文整理汇总了C#中System.Threading.SemaphoreSlim.Wait方法的典型用法代码示例。如果您正苦于以下问题:C# SemaphoreSlim.Wait方法的具体用法?C# SemaphoreSlim.Wait怎么用?C# SemaphoreSlim.Wait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.SemaphoreSlim
的用法示例。
在下文中一共展示了SemaphoreSlim.Wait方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AsyncLockShouldAllowOnlyOneThread
public void AsyncLockShouldAllowOnlyOneThread()
{
var block = new SemaphoreSlim(0, 2);
var count = 0;
var alock = new AsyncLock();
var firstCall = Task.Factory.StartNew(async () =>
{
using (await alock.LockAsync())
{
Interlocked.Increment(ref count);
block.Wait();
}
block.Wait();//keep this thread busy
});
TaskTest.WaitFor(() => count > 0);
alock.LockAsync().ContinueWith(t => Interlocked.Increment(ref count));
Assert.That(count, Is.EqualTo(1), "Only one task should have gotten past lock.");
Assert.That(firstCall.IsCompleted, Is.False, "Task should still be running.");
block.Release();
TaskTest.WaitFor(() => count > 1);
Assert.That(count, Is.EqualTo(2), "Second call should get past lock.");
Assert.That(firstCall.IsCompleted, Is.False, "First call should still be busy.");
block.Release();
}
示例2: ExtremeDisposal
public void ExtremeDisposal()
{
using (var context = CreateContext())
{
Assert.AreEqual(-1, context.Publisher.MySettings.MaxConnectionRetry, "For this test, we want the worst situation");
context.Publisher.Start(0);
Assert.IsTrue(context.Publisher.Started);
var message = new byte[] { 0, 1, 1 };
var connectionFail = new SemaphoreSlim(0);
context.Model.Setup(m => m.BasicPublish(It.IsAny<string>(), It.IsAny<string>(), context.Publisher.Props, message)).Throws(new Exception("I don't want your message anymore"));
context.Connection.Setup(c => c.CreateModel()).Callback(() => connectionFail.Release(1)).Throws(new Exception("And I don't want to accept your connection either"));
context.Publisher.Publish("test", message);
/* The way callbacks are implemented on exception throwing mocks does not garantee
* that the callback is called "after" the exception is thrown.
* If we wait for two, we are sure at least one has been finished !
*/
Assert.IsTrue(connectionFail.Wait(1000));
Assert.IsTrue(connectionFail.Wait(1000));
context.Publisher.Dispose();
context.Publisher = null; //to avoid the double dispose of Publisher
//The real test here is that eventually the Dispose method returns
Assert.Pass();
}
}
示例3: CancelBeforeWait
public static void CancelBeforeWait()
{
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
CancellationToken ct = cs.Token;
const int millisec = 100;
TimeSpan timeSpan = new TimeSpan(100);
EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "CancelBeforeWait: An OCE should have been thrown.");
EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "CancelBeforeWait: An OCE should have been thrown.");
EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "CancelBeforeWait: An OCE should have been thrown.");
semaphoreSlim.Dispose();
}
示例4: Main
static void Main(string[] args)
{
Console.Write("request count(8 recommanded): ");
var requestCount = int.Parse(Console.ReadLine());
ServicePointManager.DefaultConnectionLimit = 10000;
var alert = new AlertInSecond();
var ss = new SemaphoreSlim(requestCount, requestCount);
while (true)
{
ss.Wait();
Task.Run(OneRequest).ContinueWith(t =>
{
if (t.Status == TaskStatus.Faulted)
{
alert.AddOneFail();
}
else
{
var response = t.Result;
if (response.StatusCode == HttpStatusCode.OK)
{
alert.AddOneSuccess();
}
else
{
alert.AddOneFail();
}
}
ss.Release();
});
}
}
示例5: Construct_GivenSemaphoreSlim_ShouldLockIt
public void Construct_GivenSemaphoreSlim_ShouldLockIt()
{
//---------------Set up test pack-------------------
using (var semaphore = new SemaphoreSlim(1))
{
bool? gotLock = null;
//---------------Assert Precondition----------------
using (new LenientAutoLocker(semaphore))
{
var barrier = new Barrier(2);
Task.Run(() =>
{
barrier.SignalAndWait();
Thread.Sleep(1000);
// ReSharper disable once AccessToDisposedClosure
gotLock = semaphore.Wait(100);
});
//---------------Execute Test ----------------------
barrier.SignalAndWait();
Thread.Sleep(2000);
//---------------Test Result -----------------------
Assert.IsNotNull(gotLock);
Assert.IsFalse(gotLock.Value);
}
}
}
示例6: TryDequeue_IfMustWaitForItem_ThenProvidesItAndReturnsTrue
public void TryDequeue_IfMustWaitForItem_ThenProvidesItAndReturnsTrue()
{
DoTest((q, cts) =>
{
using (var willProvideItemAfterSleep = new SemaphoreSlim(0))
{
var tasks = new Task[]
{
new Task(() =>
{
string item;
willProvideItemAfterSleep.Wait();
Assert.IsTrue(q.TryDequeue(out item, cts.Token));
Assert.AreEqual("7", item);
}),
new Task(() =>
{
willProvideItemAfterSleep.Release();
Thread.Sleep(500);
q.Enqueue(7);
})
};
Parallel.ForEach<Task>(tasks, T => T.Start());
Task.WaitAll(tasks);
}
});
}
示例7: ProducerShouldReportCorrectAmountOfAsyncRequests
public void ProducerShouldReportCorrectAmountOfAsyncRequests()
{
var semaphore = new SemaphoreSlim(0);
var routerProxy = new FakeBrokerRouter();
//block the second call returning from send message async
routerProxy.BrokerConn0.ProduceResponseFunction = () => { semaphore.Wait(); return new ProduceResponse(); };
var router = routerProxy.Create();
using (var producer = new Producer(router, maximumAsyncRequests: 1) { BatchSize = 1 })
{
var messages = new[] { new Message("1") };
Assert.That(producer.AsyncCount, Is.EqualTo(0));
var sendTask = producer.SendMessageAsync(BrokerRouterProxy.TestTopic, messages);
TaskTest.WaitFor(() => producer.AsyncCount > 0);
Assert.That(producer.AsyncCount, Is.EqualTo(1), "One async operation should be sending.");
semaphore.Release();
sendTask.Wait(TimeSpan.FromMilliseconds(500));
Assert.That(sendTask.IsCompleted, Is.True, "Send task should be marked as completed.");
Assert.That(producer.AsyncCount, Is.EqualTo(0), "Async should now show zero count.");
}
}
示例8: TaskMain
private static void TaskMain(SemaphoreSlim semaphore)
{
bool isCompleted = false;
while (!isCompleted)
{
if (semaphore.Wait(600))
{
try
{
WriteLine($"Task {Task.CurrentId} locks the semaphore");
Task.Delay(2000).Wait();
}
finally
{
WriteLine($"Task {Task.CurrentId} releases the semaphore");
semaphore.Release();
isCompleted = true;
}
}
else
{
WriteLine($"Timeout for task {Task.CurrentId}; wait again");
}
}
}
示例9: AwaitingConnectedSpheroRunner
public AwaitingConnectedSpheroRunner(IStreamSocketWrapper streamSpheroWrapper)
{
_streamSpheroWrapper = streamSpheroWrapper;
_itemsToSendEvent = new SemaphoreSlim(1);
_itemsToSendEvent.Wait();
_commandsToSend = new Queue<CommandWithActions>();
}
示例10: Main
static int Main(string[] args)
{
SemaphoreSlim s = new SemaphoreSlim(initialCount: 1);
var cts = new CancellationTokenSource();
s.Wait();
var t = s.WaitAsync(cts.Token);
s.Release();
cts.Cancel();
if (t.Status != TaskStatus.Canceled && s.CurrentCount == 0)
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
Console.WriteLine("Expected task status to not be Canceled and s.CurrentCount == 0");
Console.WriteLine("Actual: Task: " + t.Status + "; CurrentCount: " + s.CurrentCount);
return 101;
}
}
示例11: TaskMain
static void TaskMain(SemaphoreSlim semaphore)
{
bool isCompleted = false;
while (!isCompleted)
{
if (semaphore.Wait(600))
{
try
{
Console.WriteLine("Task {0} locks the semaphore", Task.CurrentId);
Thread.Sleep(2000);
}
finally
{
Console.WriteLine("Task {0} releases the semaphore", Task.CurrentId);
semaphore.Release();
isCompleted = true;
}
}
else
{
Console.WriteLine("Timeout for task {0}; wait again",
Task.CurrentId);
}
}
}
示例12: DeclareAndUseIt
public void DeclareAndUseIt()
{
var channel = this.Connection.CreateChannel();
var exchange = channel.DeclareExchange("my6exchange", new ExchangeOptions()
{
// using default options = ephemeral
ExchangeType = RabbitExchangeType.Fanout
});
var queue1 = exchange.DeclareQueue("q1", new QueueOptions());
var queue2 = exchange.DeclareQueue("q2", new QueueOptions());
var wait = new SemaphoreSlim(2, 2);
var receivedCount = 0;
queue1.Consume(new Action<MessageEnvelope<MyDumbMessage>>(env =>
{
wait.Release();
Interlocked.Increment(ref receivedCount);
}), new ConsumerOptions());
queue2.Consume(new Action<MessageEnvelope<MyDumbMessage>>(env =>
{
wait.Release();
Interlocked.Increment(ref receivedCount);
}), new ConsumerOptions());
exchange.Send(new MyDumbMessage()); // message will be dropped
wait.Wait(TimeSpan.FromSeconds(2.0));
receivedCount.Should().Be(2);
}
示例13: CancelAfterWait
public static bool CancelAfterWait()
{
TestHarness.TestLog("* SemaphoreSlimCancellationTests.CancelAfterWait()");
bool passed = true;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0); // semaphore that will block all waiters
ThreadPool.QueueUserWorkItem(
(args) =>
{
Thread.Sleep(1000);
cancellationTokenSource.Cancel();
}
);
//Now wait.. the wait should abort and an exception should be thrown
passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(
() => semaphoreSlim.Wait(cancellationToken),
cancellationToken, "An OCE(null) should have been thrown that references the cancellationToken.");
// the token should not have any listeners.
// currently we don't expose this.. but it was verified manually
return passed;
}
示例14: RunAndBlock
private static void RunAndBlock(int threadCount)
{
ProfilerStart();
_Semaphore = new SemaphoreSlim(threadCount, threadCount);
var queue = new QueueClient();
while (!_Cancel)
{
_Semaphore.Wait();
var solicutud = queue.GetNextMessage();
if (solicutud == null)
{
Thread.Sleep(millisecondsTimeout: _NoMessageFoundSleepTimeoutMsec);
}
else
{
var t = new Thread(new ParameterizedThreadStart(RunThreaded));
t.Start(solicutud);
}
}
//Pause();
// release threads
ProfilerStop();
}
示例15: Take
public static SemaphoreLock Take(SemaphoreSlim semaphore)
{
Argument.ValidateIsNotNull(semaphore, "semaphore");
semaphore.Wait();
return new SemaphoreLock(semaphore);
}