本文整理汇总了C#中System.Threading.SemaphoreSlim.Release方法的典型用法代码示例。如果您正苦于以下问题:C# SemaphoreSlim.Release方法的具体用法?C# SemaphoreSlim.Release怎么用?C# SemaphoreSlim.Release使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.SemaphoreSlim
的用法示例。
在下文中一共展示了SemaphoreSlim.Release方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ParallelLoadGames
private const int GameCacheDuration = 43200; // 12 hours
public async Task<GameDetails[]> ParallelLoadGames(IEnumerable<int> gameIds)
{
GameDetails[] results;
var tasks = new List<Task<GameDetails>>();
using (var throttler = new SemaphoreSlim(5))
{
foreach (var gameId in gameIds)
{
await throttler.WaitAsync();
tasks.Add(Task<GameDetails>.Run(async () =>
{
try
{
Debug.WriteLine("Loading {0}...", gameId);
return await this.LoadGame(gameId, true);
}
finally
{
Debug.WriteLine("Done with {0}...", gameId);
throttler.Release();
}
}));
}
results = await Task.WhenAll(tasks);
}
return results;
}
示例2: 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);
}
示例3: 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();
}
示例4: SemaphoreSlimLock
public async Task SemaphoreSlimLock()
{
var _lock = new SemaphoreSlim( 1 );
await _lock.WaitAsync();
_lock.Release();
var start = Stopwatch.GetTimestamp();
for( var i = 0; i < Iterations; i++ ) {
await _lock.WaitAsync();
_lock.Release();
i--;
i++;
}
ReportTime( start );
}
示例5: 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);
}
});
}
示例6: 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();
});
}
}
示例7: 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);
}
示例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: EnsureList
/// <summary>
/// Ensures the list.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="file">The file.</param>
/// <param name="httpClient">The HTTP client.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="semaphore">The semaphore.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public static async Task EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, SemaphoreSlim semaphore, CancellationToken cancellationToken)
{
var fileInfo = fileSystem.GetFileInfo(file);
if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1)
{
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var temp = await httpClient.GetTempFile(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Progress = new Progress<double>(),
Url = url
}).ConfigureAwait(false);
fileSystem.CreateDirectory(Path.GetDirectoryName(file));
fileSystem.CopyFile(temp, file, true);
}
finally
{
semaphore.Release();
}
}
}
示例10: 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.");
}
}
示例11: Execute
public void Execute(IJobExecutionContext context) {
var stopwatch = new Stopwatch();
stopwatch.Start();
Logger.Info("开始抓取一号店数据");
var downloadedCategories = new YhdCategoryExtractor().Extract().Result;
var needProcessCategories = _CategoryArchiveService.Archive(downloadedCategories).OrderBy(c => c.ProductsUpdateTime);
var taskLock = new SemaphoreSlim(initialCount: 1);
var tasks = needProcessCategories.Select(async (category, index) => {
await taskLock.WaitAsync();
try {
var result = await ProcessCategoryAsync(category);
//■◆▲●□◇△○
Logger.Info(string.Join(" ", new[]{
string.Format("{0}", index + 1),
string.Format("[{0}]{1}", category.Number, category.Name),
string.Format("□{0} △{1}", result.Total, result.Changed)
}));
}
catch (Exception e) {
Logger.ErrorFormat("处理分类{0}{1}失败", e, category.Name, category.Number);
}
finally {
taskLock.Release();
}
});
Task.WaitAll(tasks.ToArray());
Logger.InfoFormat("抓取一号店数据完成,用时{0:0.#}分", stopwatch.Elapsed.TotalMinutes);
}
示例12: 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);
}
}
}
示例13: 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;
}
示例14: 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();
}
}));
}
示例15: 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();
}
}