本文整理汇总了C#中System.Threading.SemaphoreSlim.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# SemaphoreSlim.Dispose方法的具体用法?C# SemaphoreSlim.Dispose怎么用?C# SemaphoreSlim.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.SemaphoreSlim
的用法示例。
在下文中一共展示了SemaphoreSlim.Dispose方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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();
}
示例2: CancelBeforeWait
public static bool CancelBeforeWait()
{
TestHarness.TestLog("* SemaphoreSlimCancellationTests.CancelBeforeWait()");
bool passed = true;
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
CancellationToken ct = cs.Token;
const int millisec = 100;
TimeSpan timeSpan = new TimeSpan(100);
passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "An OCE should have been thrown.");
passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "An OCE should have been thrown.");
passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "An OCE should have been thrown.");
semaphoreSlim.Dispose();
return passed;
}
示例3: TheCompletePumpWithAsyncHandleMessage
public async Task TheCompletePumpWithAsyncHandleMessage()
{
var runningTasks = new ConcurrentDictionary<Task, Task>();
var semaphore = new SemaphoreSlim(100);
var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var token = tokenSource.Token;
int numberOfTasks = 0;
var pumpTask = Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
await semaphore.WaitAsync(token).ConfigureAwait(false);
Interlocked.Increment(ref numberOfTasks);
var task = HandleMessageWithCancellation(token);
runningTasks.TryAdd(task, task);
task.ContinueWith(t =>
{
semaphore.Release();
Task taskToBeRemoved;
runningTasks.TryRemove(t, out taskToBeRemoved);
}, TaskContinuationOptions.ExecuteSynchronously)
.Ignore();
}
});
await pumpTask.IgnoreCancellation().ConfigureAwait(false);
await Task.WhenAll(runningTasks.Values).IgnoreCancellation().ConfigureAwait(false);
tokenSource.Dispose();
semaphore.Dispose();
$"Consumed {numberOfTasks} messages with concurrency {semaphore.CurrentCount} in 5 seconds. Throughput {numberOfTasks / 5} msgs/s"
.Output();
}
示例4: CancellingAndGracefulShutdown
public async Task CancellingAndGracefulShutdown()
{
#region Cancellation AsAbove
var tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(TimeSpan.FromSeconds(1));
var token = tokenSource.Token;
#endregion
#region Task Tracking AsAbove
var runningTasks = new ConcurrentDictionary<Task, Task>();
#endregion
#region Limiting AsAbove
var semaphore = new SemaphoreSlim(2);
#endregion
var pumpTask = Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
#region Output
"Pumping...".Output();
#endregion
await semaphore.WaitAsync(token).ConfigureAwait(false);
#region HandleMessage AsAbove
var runningTask = HandleMessageWithCancellation(token);
runningTasks.TryAdd(runningTask, runningTask);
#endregion
#region Releasing Semaphore & Housekeeping AsAbove
runningTask.ContinueWith(t =>
{
#region Output
"... done".Output();
#endregion
semaphore.Release();
#region Housekeeping
Task taskToBeRemoved;
runningTasks.TryRemove(t, out taskToBeRemoved);
#endregion
}, TaskContinuationOptions.ExecuteSynchronously)
.Ignore();
#endregion
}
}, CancellationToken.None);
await pumpTask.IgnoreCancellation().ConfigureAwait(false);
#region Awaiting completion
#region Output
"Pump finished".Output();
#endregion
await Task.WhenAll(runningTasks.Values).IgnoreCancellation().ConfigureAwait(false);
#region Output
"All receives finished".Output();
#endregion
tokenSource.Dispose();
semaphore.Dispose();
#endregion
}
示例5: ExecuteAsync
public override async Task ExecuteAsync(CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(this._bucketName))
{
throw new InvalidOperationException("The bucketName specified is null or empty!");
}
SemaphoreSlim asyncThrottler = null;
CancellationTokenSource internalCts = null;
try
{
asyncThrottler = new SemaphoreSlim(_config.ConcurrentServiceRequests);
internalCts = new CancellationTokenSource();
var internalCancellationToken = internalCts.Token;
ListMultipartUploadsResponse listResponse = new ListMultipartUploadsResponse();
var pendingTasks = new List<Task<AbortMultipartUploadResponse>>();
do
{
ListMultipartUploadsRequest listRequest = ConstructListMultipartUploadsRequest(listResponse);
listResponse = await this._s3Client.ListMultipartUploadsAsync(listRequest, cancellationToken)
.ConfigureAwait(continueOnCapturedContext: false);
foreach (MultipartUpload upload in listResponse.MultipartUploads)
{
cancellationToken.ThrowIfCancellationRequested();
if (internalCancellationToken.IsCancellationRequested)
{
// Operation cancelled as one of the AbortMultipartUpload requests failed with an exception,
// don't schedule any more AbortMultipartUpload tasks.
// Don't throw an OperationCanceledException here as we want to process the
// responses and throw the original exception.
break;
}
if (upload.Initiated < this._initiatedDate)
{
await asyncThrottler.WaitAsync(cancellationToken)
.ConfigureAwait(continueOnCapturedContext: false);
var abortRequest = ConstructAbortMultipartUploadRequest(upload);
var task = AbortAsync(abortRequest, internalCts, cancellationToken, asyncThrottler);
pendingTasks.Add(task);
}
}
}
while (listResponse.IsTruncated);
await WhenAllOrFirstExceptionAsync(pendingTasks,cancellationToken);
}
finally
{
if (internalCts != null)
internalCts.Dispose();
if (asyncThrottler!=null)
asyncThrottler.Dispose();
}
}
示例6: RunSemaphoreSlimTest4_Dispose
/// <summary>
/// Test SemaphoreSlim Dispose
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called after Dispose</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest4_Dispose(int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType)
{
Exception exception = null;
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
semaphore.Dispose();
CallSemaphoreAction(semaphore, action, null);
}
catch (Exception ex)
{
exception = ex;
}
// The code threw excption and it is not expected because the excyptionType param is null
if (exceptionType == null && exception != null)
{
string methodFailed = "RunSemaphoreSlimTest4_Dispose(" + initial + "," + maximum + "," + action + "): FAILED. ";
Assert.True(false, string.Format(methodFailed + "Dispose failed, the code threw an exception, and it is not supposed to."));
}
// Compare both exception types in case of the code threw exception
if (exception != null && !Type.Equals(exception.GetType(), exceptionType))
{
string methodFailed = "RunSemaphoreSlimTest4_Dispose(" + initial + "," + maximum + "," + action + "): FAILED. ";
Assert.True(false, string.Format(methodFailed + "Dispose failed, Excption types do not match"));
}
}
示例7: if
/// <summary>
/// Call specific SemaphoreSlim method or property
/// </summary>
/// <param name="semaphore">The SemaphoreSlim instance</param>
/// <param name="action">The action name</param>
/// <param name="param">The action parameter, null if it takes no parameters</param>
/// <returns>The action return value, null if the action returns void</returns>
private static object CallSemaphoreAction
(SemaphoreSlim semaphore, SemaphoreSlimActions? action, object param)
{
if (action == SemaphoreSlimActions.Wait)
{
if (param is TimeSpan)
{
return semaphore.Wait((TimeSpan)param);
}
else if (param is int)
{
return semaphore.Wait((int)param);
}
semaphore.Wait();
return null;
}
else if (action == SemaphoreSlimActions.WaitAsync)
{
if (param is TimeSpan)
{
return semaphore.WaitAsync((TimeSpan)param).Result;
}
else if (param is int)
{
return semaphore.WaitAsync((int)param).Result;
}
semaphore.WaitAsync().Wait();
return null;
}
else if (action == SemaphoreSlimActions.Release)
{
if (param != null)
{
return semaphore.Release((int)param);
}
return semaphore.Release();
}
else if (action == SemaphoreSlimActions.Dispose)
{
semaphore.Dispose();
return null;
}
else if (action == SemaphoreSlimActions.CurrentCount)
{
return semaphore.CurrentCount;
}
else if (action == SemaphoreSlimActions.AvailableWaitHandle)
{
return semaphore.AvailableWaitHandle;
}
return null;
}
示例8: RunExperiment
public Statistic RunExperiment(CalculationParameters param)
{
CheckParameters(param);
var sw = Stopwatch.StartNew();
SimulatedGamesCount = 0;
Card player_card1 = param.PlayerCard1;
Card player_card2 = param.PlayerCard2;
Card[] open_cards = GetOpenCards(param);
ValidateInputCards(player_card1, player_card2, open_cards);
Card[] cards = GetAllCards();
Card[] free_cards = GetFreeCards(cards, player_card1, player_card2, open_cards);
var stat = new StatisticInternal();
stat.Init();
int parallelLevel = param.ParallelLevel;
#if OneThreadForDBG
parallelLevel = 1;
#endif
int enemyPlayersCount = param.EnemyPlayersCount;
int gameNumber = param.GameNumber;
var semaphore = new SemaphoreSlim(parallelLevel);
var countdown = new CountdownEvent(gameNumber);
for (int i = 0; i < gameNumber; i++)
{
param.CancelToken.ThrowIfCancellationRequested();
if (param.TimeLimit.HasValue
&& sw.Elapsed > param.TimeLimit.Value)
{
countdown.Signal(gameNumber - i);
break;
}
semaphore.Wait();
SimulatedGamesCount++;
Action action =
() =>
{
try
{
SimulateGame(player_card1, player_card2, open_cards, free_cards, enemyPlayersCount, stat, param);
}
finally
{
semaphore.Release();
countdown.Signal();
}
};
if (parallelLevel == 1)
{
action();
}
else
{
Task.Factory.StartNew(action);
}
}
countdown.Wait();
countdown.Dispose();
semaphore.Dispose();
Statistic public_stat = PreparePublicStatistic(stat);
return public_stat;
}
示例9: SemaphoreSlim
/// <summary>
/// Test SemaphoreSlim Dispose
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called after Dispose</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static bool RunSemaphoreSlimTest4_Dispose
(int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType)
{
TestHarness.TestLog("Dispose(" + initial + "," + maximum + "," + action + ")");
Exception exception = null;
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
semaphore.Dispose();
CallSemaphoreAction(semaphore,action,null);
}
catch (Exception ex)
{
exception = ex;
}
// The code threw excption and it is not expected because the excyptionType param is null
if (exceptionType == null && exception != null)
{
TestHarness.TestLog("Dispose failed, the code threw an exception, and it is not supposed to.");
return false;
}
// Compare both exception types in case of the code threw exception
if (exception != null && !Type.Equals(exception.GetType(), exceptionType))
{
TestHarness.TestLog("Dispose failed, Excption types do not match");
return false;
}
TestHarness.TestLog("Dispose succeeded");
return true;
}
示例10: ProcessAlertQueueAsync
private async Task ProcessAlertQueueAsync()
{
Logger.Instance.LogDebug("Starting alert processing.");
DisplayAlertEvent currentAlert;
do
{
lock (_lock)
{
var count = _alertQueue.Count;
Logger.Instance.LogDebug("Alert queue contains {0} items", count);
currentAlert = count == 0
? null
: _alertQueue.Peek();
}
var semaphore = new SemaphoreSlim(0, 1);
var viewEnabled = true;
if (currentAlert != null)
{
var viewContainer = new StackLayout {Orientation = StackOrientation.Vertical};
viewContainer.GestureRecognizers.Add(new TapGestureRecognizer
{
NumberOfTapsRequired = 1,
Command = new Command(() =>
{
if (viewEnabled)
{
semaphore.Release();
}
if (currentAlert.TapAction != null)
{
currentAlert.TapAction();
}
})
});
currentAlert.Dismissed += (sender, args) =>
{
if (viewEnabled)
{
semaphore.Release();
}
};
viewContainer.Children.Add(currentAlert.Content);
Device.BeginInvokeOnMainThread(() => _overlayContainer.Children.Add(viewContainer));
if (currentAlert.AutoDismiss)
{
var displayTime = currentAlert.DisplayTime ?? TimeSpan.FromSeconds(5);
await semaphore.WaitAsync(displayTime);
}
else
{
await semaphore.WaitAsync();
}
viewEnabled = false;
Device.BeginInvokeOnMainThread(() => _overlayContainer.Children.Remove(viewContainer));
lock (_lock)
{
_alertQueue.Dequeue();
}
semaphore.Dispose();
}
} while (currentAlert != null);
}