本文整理汇总了C#中System.Threading.SemaphoreSlim类的典型用法代码示例。如果您正苦于以下问题:C# SemaphoreSlim类的具体用法?C# SemaphoreSlim怎么用?C# SemaphoreSlim使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SemaphoreSlim类属于System.Threading命名空间,在下文中一共展示了SemaphoreSlim类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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();
}
}
示例2: TestCancelWaitAsyncInternal
private async Task TestCancelWaitAsyncInternal()
{
var r = new Random();
var s = new SemaphoreSlim(1);
await Task.WhenAll(Enumerable.Range(0, 100).Select(async i =>
{
var ct = CancellationToken.None;
if ((i % 5) == 0)
{
var cts = new CancellationTokenSource();
var t = Task.Delay(1).ContinueWith(_ => cts.Cancel());
ct = cts.Token;
}
try
{
await s.WaitAsync(ct);
await Delay(r, ct).ConfigureAwait(false);
}
catch (TestException) { }
catch (OperationCanceledException) { }
finally
{
s.Release();
}
}));
}
示例3: GetWithRetryAsync
public static async Task<HttpResponseMessage> GetWithRetryAsync(this HttpClient client, string url, SemaphoreSlim semaphore, params int[] retryDelay)
{
if (retryDelay.Any(delay => delay <= 0))
{
throw new ArgumentException("Delay should be greate than 0.", nameof(retryDelay));
}
await semaphore.WaitAsync();
try
{
int retryCount = 0;
while (true)
{
try
{
return await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
}
catch (TaskCanceledException)
{
if (retryCount >= retryDelay.Length)
{
throw;
}
}
await Task.Delay(retryDelay[retryCount]);
retryCount++;
}
}
finally
{
semaphore.Release();
}
}
示例4: DiskCache
/// <summary>
/// Initializes a new instance of the <see cref="FFImageLoading.Cache.DiskCache"/> class.
/// </summary>
/// <param name="basePath">Base path.</param>
/// <param name="version">Version.</param>
public DiskCache(string basePath, string version)
{
// Can't use minilogger here, we would have too many dependencies
System.Diagnostics.Debug.WriteLine("DiskCache path: " + basePath);
this.basePath = basePath;
if (!Directory.Exists(basePath))
Directory.CreateDirectory(basePath);
this.journalPath = Path.Combine(basePath, JournalFileName);
this.version = version;
this.lockJournal = new object();
this.fileWriteLock = new SemaphoreSlim(initialCount: 1);
this.fileWritePendingTasks = new ConcurrentDictionary<string, byte>();
try
{
InitializeWithJournal ();
}
catch
{
Directory.Delete (basePath, true);
Directory.CreateDirectory (basePath);
}
ThreadPool.QueueUserWorkItem(CleanCallback);
}
示例5: ExclusiveTask
private async Task ExclusiveTask(SemaphoreSlim s, Integer count, int seed, int iteration, bool due)
{
var r = new Random(seed);
if (due)
{
try
{
await Delay(r).ConfigureAwait(false);
}
catch { }
}
for (int i = 0; i < iteration; i++)
{
int localCount = 0;
try
{
await s.WaitAsync();
localCount = count.Value;
await Delay(r).ConfigureAwait(false);
}
catch (TestException) { }
finally
{
count.Value = localCount + 1;
s.Release();
}
}
}
示例6: Main
static void Main(string[] args)
{
// initialize the semaphores
semA = new SemaphoreSlim(2);
semB = new SemaphoreSlim(2);
// define the number of tasks we will use
int taskCount = 10;
// initialize the barrier
cdEvent = new CountdownEvent(taskCount);
Task[] tasks = new Task[10];
for (int i = 0; i < taskCount; i++) {
tasks[i] = Task.Factory.StartNew((stateObject) => {
InitialMethod((int)stateObject);
Console.WriteLine("Task {0} completed", Task.CurrentId);
}, i);
}
// wait for all of the tasks to have reached a terminal method
cdEvent.Wait();
// throw an exception to force the debugger to break
throw new Exception();
}
示例7: ServiceContext
private ServiceContext()
{
_Slots = new List<ServiceSlot>();
_StartSemaphore = new SemaphoreSlim(0);
_StopSemaphore = new SemaphoreSlim(0);
}
示例8: ConcurrentRunner
public ConcurrentRunner(int maxThread, int loopEach, AutoResetEvent signal = null)
{
this.maxThread = maxThread;
this.loopEach = loopEach;
this.semaphore = new SemaphoreSlim(0, maxThread);
this.signal = signal;
}
示例9: Consume
// WIP, not producing useful numbers yet. Assumes one partition.
public static async Task<long> Consume(string broker, string topic)
{
long n = 0;
var topicConfig = new TopicConfig();
topicConfig["auto.offset.reset"] = "smallest";
var config = new Config()
{
GroupId = "benchmark-consumer",
DefaultTopicConfig = topicConfig
};
using (var consumer = new EventConsumer(config, broker))
{
var signal = new SemaphoreSlim(0, 1);
consumer.OnMessage += (obj, msg) =>
{
n += 1;
};
consumer.OnEndReached += (obj, end) =>
{
Console.WriteLine($"End reached");
signal.Release();
};
consumer.Subscribe(new List<string>{topic});
consumer.Start();
await signal.WaitAsync();
Console.WriteLine($"Shutting down");
}
return n;
}
示例10: Authorize
public async Task<TokenPair> Authorize(string clientId, string clientSecret, IEnumerable<string> scopes)
{
string uri = string.Format("/LoginPage.xaml?authEndpoint={0}&clientId={1}&scope={2}",
authEndpoint,
clientId,
string.Join(" ", scopes));
SemaphoreSlim semaphore = new SemaphoreSlim(0, 1);
Observable.FromEvent<NavigatingCancelEventHandler, NavigatingCancelEventArgs>(
h => new NavigatingCancelEventHandler(h),
h => this.frame.Navigating += h,
h => this.frame.Navigating -= h)
.SkipWhile(h => h.EventArgs.NavigationMode != NavigationMode.Back)
.Take(1)
.Subscribe(e => semaphore.Release());
frame.Navigate(new Uri(uri, UriKind.Relative));
await semaphore.WaitAsync();
string authorizationCode = (string)PhoneApplicationService.Current.State["OAuth_Demo.AuthorizationCode"];
return await RequestAccessToken(authorizationCode, clientId, clientSecret);
}
示例11: AcquireAuthorizationAsync
public async Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, IDictionary<string, string> additionalHeaders, CallState callState)
{
returnedUriReady = new SemaphoreSlim(0);
Authenticate(authorizationUri, redirectUri, additionalHeaders, callState);
await returnedUriReady.WaitAsync().ConfigureAwait(false);
return authorizationResult;
}
示例12: BaseClient
/// <summary>
/// Initialises a new instance of the <see cref="BaseClient"/> class.
/// </summary>
/// <param name="byteStream">The byte stream.</param>
/// <param name="token">The token.</param>
protected BaseClient(IByteStream byteStream, CancellationToken token)
{
this.ByteStream = byteStream;
this.SendRateLimit = new SemaphoreSlim(1);
this.InternalCancellation = new CancellationTokenSource();
token.Register(() => this.InternalCancellation.Cancel());
}
示例13: AwaitingConnectedSpheroRunner
public AwaitingConnectedSpheroRunner(IStreamSocketWrapper streamSpheroWrapper)
{
_streamSpheroWrapper = streamSpheroWrapper;
_itemsToSendEvent = new SemaphoreSlim(1);
_itemsToSendEvent.Wait();
_commandsToSend = new Queue<CommandWithActions>();
}
示例14: 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);
}
}
}
示例15: BufferStream
internal BufferStream()
{
_readLock = new SemaphoreSlim(1, 1);
_writeLock = new SemaphoreSlim(1, 1);
_bufferedData = new ConcurrentQueue<byte[]>();
_readWaitingForData = new TaskCompletionSource<object>();
}