public AsyncLock() { m_semaphore = new AsyncSemaphore(1); #if NET4_0 m_releaser = TaskEx.FromResult(new Releaser(this)); #else m_releaser = Task.FromResult(new Releaser(this)); #endif }
public void ItCompletesTheTasksWhenWaitAsyncIsCalledSampleTimes() { var asyncSemaphore = new AsyncSemaphore(SampleTimes); var tasks = new Task[SampleTimes]; for (int i = 0; i < SampleTimes; i++) { tasks[i] = asyncSemaphore.WaitAsync(); } var task = Task.WhenAll(tasks); task.Wait(TimeSpan.FromSeconds(1)); Assert.IsTrue(task.IsCompleted); }
public void ItReturnsNewUncompletedTasksWhenWaitAsyncIsCalledSamplePlusOneTimes() { var asyncSemaphore = new AsyncSemaphore(SampleTimes); var tasks = new Task[SampleTimes]; for (int i = 0; i < SampleTimes; i++) { tasks[i] = asyncSemaphore.WaitAsync(); } var task = Task.WhenAll(tasks); task.Wait(TimeSpan.FromSeconds(1)); var newTask = asyncSemaphore.WaitAsync(); Assert.IsTrue(newTask != task && task.IsCompleted && !newTask.IsCompleted); }
public async Task TooManyReleases_CopyOfStruct() { var sem = new AsyncSemaphore(2); AsyncSemaphore.Releaser releaser1 = await sem.EnterAsync(); AsyncSemaphore.Releaser releaser2 = await sem.EnterAsync(); // Assigning the releaser struct to another local variable copies it. AsyncSemaphore.Releaser releaser2Copy = releaser2; // Dispose of each copy of the releaser. // The double-release is undetectable. The semaphore should be back at capacity 2. releaser2.Dispose(); Assert.Equal(1, sem.CurrentCount); releaser2Copy.Dispose(); Assert.Equal(2, sem.CurrentCount); releaser1.Dispose(); Assert.Equal(3, sem.CurrentCount); }
protected virtual void Dispose(bool disposing) { if (!disposing) { return; } try { if (this.connection != null) { lock (this.thisLock) { if (this.connection != null) { this.connection.Close(); this.connection = null; } } } } finally { try { if (this.semaphore != null) { this.semaphore.Dispose(); this.semaphore = null; } } finally { if (File.Exists(this.pathSchema)) { File.Delete(this.pathSchema); } } } }
public async Task DisposeLock() { //**************************************** var MyLock = new AsyncSemaphore(); //**************************************** var MyDispose = MyLock.DisposeAsync(); try { MyLock.Take().GetAwaiter().GetResult().Dispose(); } catch (ObjectDisposedException) { } //**************************************** await MyDispose; Assert.AreEqual(0, MyLock.WaitingCount, "Still waiting for Semaphore"); Assert.AreEqual(MyLock.MaxCount, MyLock.CurrentCount, "Semaphore still held"); }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { AsyncSemaphore[] semaphores = Interlocked.Exchange(ref _semaphores, null); if (semaphores == null) { return; } List <Exception> ex = null; for (int i = 0; i < semaphores.Length; i++) { try { AsyncSemaphore sem = Interlocked.Exchange(ref semaphores[i], null); sem?.Release(); } catch (Exception e) { if (ex == null) { ex = new List <Exception>(); } ex.Add(e); } } if (ex == null || ex.Count < 1) { return; } // ReSharper disable once AssignNullToNotNullAttribute if (ex.Count < 2) { ex[0].ReThrow(); } throw new AggregateException(ex); }
public SemanticChangeProcessor( IAsynchronousOperationListener listener, int correlationId, Workspace workspace, IncrementalAnalyzerProcessor documentWorkerProcessor, int backOffTimeSpanInMS, int projectBackOffTimeSpanInMS, CancellationToken cancellationToken) : base(listener, backOffTimeSpanInMS, cancellationToken) { this.gate = new AsyncSemaphore(initialCount: 0); this.correlationId = correlationId; this.workspace = workspace; this.processor = new ProjectProcessor(listener, correlationId, workspace, documentWorkerProcessor, projectBackOffTimeSpanInMS, cancellationToken); this.workGate = new NonReentrantLock(); this.pendingWork = new Dictionary <DocumentId, Data>(); Start(); }
public RazorProjectHostBase( IUnconfiguredProjectCommonServices commonServices, [Import(typeof(VisualStudioWorkspace))] Workspace workspace, RazorProjectChangePublisher razorProjectChangePublisher) : base(commonServices.ThreadingService.JoinableTaskContext) { if (commonServices == null) { throw new ArgumentNullException(nameof(commonServices)); } if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } CommonServices = commonServices; _workspace = workspace; _lock = new AsyncSemaphore(initialCount: 1); _currentDocuments = new Dictionary <string, HostDocument>(FilePathComparer.Instance); _razorProjectChangePublisher = razorProjectChangePublisher; }
public async Task TryTakeLock() { //**************************************** var MyLock = new AsyncSemaphore(); //**************************************** Assert.True(MyLock.TryTake(out var MyHandle), "Lock not taken"); var MyWait = MyLock.Take(); Assert.IsFalse(MyWait.IsCompleted, "Nested lock taken"); MyHandle.Dispose(); MyHandle = await MyWait; MyHandle.Dispose(); //**************************************** Assert.AreEqual(0, MyLock.WaitingCount, "Still waiting for Semaphore"); Assert.AreEqual(MyLock.MaxCount, MyLock.CurrentCount, "Semaphore still held"); }
public async Task LockCancelLockLock() { //**************************************** var MyLock = new AsyncSemaphore(); var Resource = false; ValueTask <AsyncSemaphore.Instance> MyWaiter1, MyWaiter2; //**************************************** using (var MySource = new CancellationTokenSource()) { using (await MyLock.Take()) { MyWaiter1 = MyLock.Take(MySource.Token); MyWaiter2 = MyLock.Take(); MySource.Cancel(); Assert.IsTrue(MyWaiter1.IsCanceled, "Wait not cancelled"); Assert.IsFalse(MyWaiter2.IsCompleted, "Nested lock taken"); Resource = true; } } //**************************************** await MyWaiter2; Assert.IsTrue(Resource, "Block not entered"); MyWaiter2.Result.Dispose(); Assert.AreEqual(0, MyLock.WaitingCount, "Still waiting for Semaphore"); Assert.AreEqual(MyLock.MaxCount, MyLock.CurrentCount, "Semaphore still held"); }
public void TryTakeCancel() { //**************************************** var MyLock = new AsyncSemaphore(); //**************************************** Assert.True(MyLock.TryTake(out var MyHandle1), "Lock not taken"); using (var MyCancel = new CancellationTokenSource()) { MyCancel.CancelAfter(50); var StartTime = DateTime.Now; try { MyLock.TryTake(out _, MyCancel.Token); Assert.Fail("Nested lock taken"); } catch (OperationCanceledException) { } var EndTime = DateTime.Now; Assert.GreaterOrEqual((EndTime - StartTime).TotalMilliseconds, 50.0, "Finished too early"); } MyHandle1.Dispose(); //**************************************** Assert.AreEqual(0, MyLock.WaitingCount, "Still waiting for Semaphore"); Assert.AreEqual(MyLock.MaxCount, MyLock.CurrentCount, "Semaphore still held"); }
public void TryTakeMaxTime() { //**************************************** var MyLock = new AsyncSemaphore(); //**************************************** Assert.True(MyLock.TryTake(out var MyHandle1), "Lock not taken"); var StartTime = DateTime.Now; Assert.False(MyLock.TryTake(out _, TimeSpan.FromMilliseconds(50)), "Nested lock taken"); var EndTime = DateTime.Now; MyHandle1.Dispose(); //**************************************** Assert.GreaterOrEqual((EndTime - StartTime).TotalMilliseconds, 50.0, "Finished too early"); Assert.AreEqual(0, MyLock.WaitingCount, "Still waiting for Semaphore"); Assert.AreEqual(MyLock.MaxCount, MyLock.CurrentCount, "Semaphore still held"); }
public MacRazorProjectHostBase( DotNetProject project, ProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, ProjectSnapshotManagerBase projectSnapshotManager, ProjectConfigurationFilePathStore projectConfigurationFilePathStore) { if (project is null) { throw new ArgumentNullException(nameof(project)); } if (projectSnapshotManagerDispatcher is null) { throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); } if (projectSnapshotManager is null) { throw new ArgumentNullException(nameof(projectSnapshotManager)); } if (projectConfigurationFilePathStore is null) { throw new ArgumentNullException(nameof(projectConfigurationFilePathStore)); } DotNetProject = project; ProjectSnapshotManagerDispatcher = projectSnapshotManagerDispatcher; _projectSnapshotManager = projectSnapshotManager; ProjectConfigurationFilePathStore = projectConfigurationFilePathStore; _onProjectChangedInnerSemaphore = new AsyncSemaphore(initialCount: 1); _projectChangedSemaphore = new AsyncSemaphore(initialCount: 1); _currentDocuments = new Dictionary <string, HostDocument>(FilePathComparer.Instance); AttachToProject(); }
public AsyncLock() { m_semaphore = new AsyncSemaphore(1); m_releaser = Task.FromResult(new Releaser(this)); }
public MainPage() { this.InitializeComponent(); _ = new AsyncSemaphore(1); new MessageDialog("dsgfadsf").ShowAsync().AsTask().Forget(); }
/// <summary> /// Disposes of managed resources. /// </summary> /// <param name="asyncSemaphore">The <see cref="T:Nito.AsyncEx.AsyncSemaphore"/> instance.</param> public static void Dispose(this AsyncSemaphore asyncSemaphore) { // None to do. The original implementation of Nito.AsyncEx.AsyncSemaphore is not IDisposable. }
public void WhenClientsCountIsLessThen_SemaphoreShouldNotMakeClientsWaitedAsync() { var sut = new AsyncSemaphore(3); ConcurrentAssert.EnsureThatTaskIsCompleted(Task.WhenAll(sut.WaitAsync(), sut.WaitAsync())); }
public DialogService() { _lock = new AsyncSemaphore(1); }
public void ItReturnsTaskWhenWaitAsyncIsCalled() { var asyncSemaphore = new AsyncSemaphore(SampleTimes); Assert.IsInstanceOfType(asyncSemaphore.WaitAsync(), typeof(Task)); }
public CommaDelimitedFileAdapter(string filePath, IReadOnlyCollection<string> columnNames) { if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentNullException(CommaDelimitedFileAdapter.ArgumentNameFilePath); } if (null == columnNames) { throw new ArgumentNullException(CommaDelimitedFileAdapter.ArgumentNameColumnNames); } this.headers = this.ComposeHeaders(columnNames); this.headersNormalized = this .headers .Select( (string item) => item.ToUpperInvariant()) .ToArray(); this.header = string.Join(CommaDelimitedFileAdapter.Comma, this.headers); this.FilePath = System.IO.Path.GetFullPath(filePath); this.pathFolder = System.IO.Path.GetDirectoryName(this.FilePath); if (!Directory.Exists(this.pathFolder)) { Directory.CreateDirectory(pathFolder); } this.fileName = System.IO.Path.GetFileName(FilePath); this.pathSchema = System.IO.Path.Combine(this.pathFolder, CommaDelimitedFileAdapter.SchemaFileName); this.schema = string.Format( CultureInfo.InvariantCulture, CommaDelimitedFileAdapter.SchemaFileTemplate, this.fileName); this.ValidateFile(columnNames); string connectionString = string.Format( CultureInfo.InvariantCulture, CommaDelimitedFileAdapter.ConnectionStringTemplate, pathFolder); this.connection = new OleDbConnection(connectionString); this.connection.Open(); this.semaphore = new AsyncSemaphore(1); }
/// <summary> /// Reset the number of connections we allow to remote machines at once. /// </summary> /// <param name="numberOfConnections"></param> /// <remarks> /// This doesn't wait to drain current connections. It just opens up new slots - the old connections will /// eventually terminate and the system will drift towards the proper number of active connections. /// </remarks> public static void ResetAllowedSimultaniousConnections(uint numberOfConnections) { _gConnectionInterlockLimiter = new AsyncSemaphore(numberOfConnections); }
/// <summary> /// Downloads binary (non-"Google Docs") file. /// </summary> /// <param name="service">Google Drive service used to download a file.</param> /// <param name="file">Meta-information about file to download.</param> /// <param name="semaphore">Semaphore used to throttle downloading process.</param> /// <param name="unitsOfWork">Abstract units of work assigned to download this file. Used in progress reporting.</param> /// <param name="directories">Dictionary that contains possible directories to save a file.</param> /// <returns>Information about downloaded file, null if downloading failed.</returns> /// <exception cref="InternalErrorException">Something is wrong with downloader code itself.</exception> public async Task <DownloadedFile> DownloadBinaryFile( DriveService service, File file, AsyncSemaphore semaphore, int unitsOfWork, IDictionary <File, IEnumerable <DirectoryInfo> > directories) { this.Info = file.Name; this.Estimation = unitsOfWork; if (file.Size.HasValue && (file.Size.Value == 0)) { try { var fileName = FileDownloadUtils.GetFileName(file, directories); System.IO.File.Create(fileName); this.Done(); return(new DownloadedFile(file, fileName)); } catch (Exception e) { this.Log.LogError($"Saving zero-length file '{file.Name}' error.", e); this.StatusAccumulator.FailureOccurred(); throw; } } var request = service.Files.Get(file.Id); request.MediaDownloader.ProgressChanged += downloadProgress => { switch (downloadProgress.Status) { case DownloadStatus.NotStarted: break; case DownloadStatus.Downloading: this.Progress = (int)(downloadProgress.BytesDownloaded * unitsOfWork / (file.Size ?? 1)); break; case DownloadStatus.Completed: this.Progress = this.Estimation; break; case DownloadStatus.Failed: this.Progress = this.Estimation; if (!this.CancellationToken.IsCancellationRequested) { this.Status = Status.Error; this.Log.LogError($"Downloading file '{file.Name}' error.", downloadProgress.Exception); this.StatusAccumulator.FailureOccurred(); } break; default: throw new InternalErrorException("DownloadStatus enum contains unknown value."); } }; await semaphore.WaitAsync(); this.Log.LogDebugMessage($"Starting to download '{file.Name}' binary file."); try { var fileName = FileDownloadUtils.GetFileName(file, directories); using (var fileStream = new FileStream(fileName, FileMode.Create)) { await GoogleRequestHelper.Execute( ct => request.DownloadAsync(fileStream, ct), this.CancellationToken, GoogleRequestHelper.Cooldown *Utils.Constants.DownloadThreadsCount); } var fileInfo = FileDownloadUtils.CorrectFileTimes(file, fileName); this.Log.LogDebugMessage($"File '{file.Name}' downloading finished, saved as {fileInfo.FullName}."); this.StatusAccumulator.SuccessItem(); this.Done(); return(new DownloadedFile(file, fileInfo.FullName)); } catch (Exception e) { if (this.CancellationToken.IsCancellationRequested) { throw; } this.Log.LogError($"Downloading file '{file.Name}' error.", e); this.StatusAccumulator.FailureOccurred(); throw; } finally { semaphore.Release(); } }
public MaxConnectionsEnforcer(int maxConnections) { semaphore = new AsyncSemaphore(maxConnections); }
/// <summary> /// A probe attempt to one destination. /// </summary> private async Task ProbeDestinationAsync(DestinationInfo destination, AsyncSemaphore semaphore, CancellationToken cancellationToken) { // Conduct a dither for every endpoint probe to optimize concurrency. var randomDither = _randomFactory.CreateRandomInstance(); await _timer.Delay(TimeSpan.FromMilliseconds(randomDither.Next(_ditheringIntervalInMilliseconds)), cancellationToken); var outcome = HealthProbeOutcome.Unknown; string logDetail = null; // Enforce max concurrency. await semaphore.WaitAsync(); Log.ProberStarted(_logger, BackendId, destination.DestinationId); try { using (var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token)) { // Set up timeout and start probing. timeoutCts.CancelAfter(_httpTimeoutInterval, _timer); var response = await _operationLogger.ExecuteAsync( "ReverseProxy.Service.HealthProbe", () => _backendProbeHttpClient.GetAsync(new Uri(new Uri(destination.Config.Value.Address, UriKind.Absolute), _healthControllerUrl), timeoutCts.Token)); // Collect response status. outcome = response.IsSuccessStatusCode ? HealthProbeOutcome.Success : HealthProbeOutcome.HttpFailure; logDetail = $"Received status code {(int)response.StatusCode}"; } } catch (HttpRequestException ex) { // If there is a error during the http request process. Swallow the error and log error message. outcome = HealthProbeOutcome.TransportFailure; logDetail = ex.Message; } catch (OperationCanceledException) { // If the cancel requested by our StopAsync method. It is a expected graceful shut down. if (_cts.IsCancellationRequested) { outcome = HealthProbeOutcome.Canceled; logDetail = "Operation deliberately canceled"; throw; } else { outcome = HealthProbeOutcome.Timeout; logDetail = $"Health probe timed out after {Config.HealthCheckOptions.Interval.TotalSeconds} second"; } } catch (Exception ex) { throw new Exception($"Prober for '{destination.DestinationId}' encounters unexpected exception.", ex); } finally { if (outcome != HealthProbeOutcome.Canceled) { // Update the health state base on the response. var healthState = outcome == HealthProbeOutcome.Success ? DestinationHealth.Healthy : DestinationHealth.Unhealthy; destination.DynamicState.Value = new DestinationDynamicState(healthState); Log.ProberResult(_logger, destination.DestinationId, outcome, logDetail); } // The probe operation is done, release the semaphore to allow other probes to proceed. semaphore.Release(); } }
public NonblockingChannel(ConcurrentQueue <T> writeQueue, AsyncSemaphore readSemaphore, AsyncSemaphore writeSemaphore) { this.writeQueue = writeQueue; this.readSemaphore = readSemaphore; this.writeSemaphore = writeSemaphore; }
public AsyncLock() { _semaphore = new AsyncSemaphore(1); _releaser = Task.Factory.FromResult(new Releaser(this)); }
/// <summary> /// Initializes a new instance of the BlobReadStrea class. /// </summary> /// <param name="blob">Blob reference to read from</param> /// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param> /// <param name="options">An object that specifies any additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param> internal BlobReadStream(ICloudBlob blob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) : base(blob, accessCondition, options, operationContext) { this.parallelOperationSemaphore = new AsyncSemaphore(1); }
public ProjectLocalSecretsManager(IProjectPropertiesProvider propertiesProvider, Lazy <IServiceProvider> serviceProvider) { _propertiesProvider = propertiesProvider ?? throw new ArgumentNullException(nameof(propertiesProvider)); _services = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _semaphore = new AsyncSemaphore(1); }
public void Id_IsNotZero() { AsyncSemaphore semaphore = new AsyncSemaphore(0); Assert.NotEqual(0, semaphore.Id); }
public void SetConcurrentCalls(int concurrentCalls) { _asyncSemaphore = new AsyncSemaphore(concurrentCalls); Config.MaxConcurrentCalls = concurrentCalls; }
/// <inheritdoc/> public void Start(AsyncSemaphore semaphore) { // Start background work, wake up for every interval(set in backend config). _backgroundPollingLoopTask = TaskScheduler.Current.Run(() => ProbeDestinationsAsync(semaphore, _cts.Token)); }
public AsyncLock() { _semaphore = new AsyncSemaphore(); _releaser = Task.FromResult((IDisposable) new Releaser(this)); }
public MongoIdentityStorage(string clusterName, IMongoCollection <PidLookupEntity> pids, int maxConcurrency = 50) { _asyncSemaphore = new AsyncSemaphore(maxConcurrency); _clusterName = clusterName; _pids = pids; }
/// <summary> /// Asynchronously downloads meta-information for one file. /// </summary> /// <param name="service">Google Drive service that is used to download files metainformation.</param> /// <param name="file">File with filled Id field.</param> /// <param name="semaphore">Semaphore used to throttle downloading process.</param> /// <returns>Asynchronous task that downloads meta-information.</returns> private async Task <File> DownloadFileMetaInformation(DriveService service, File file, AsyncSemaphore semaphore) { var fileInfoRequest = service.Files.Get(file.Id); fileInfoRequest.Fields = "*"; await semaphore.WaitAsync(); try { var fileInfo = await GoogleRequestHelper.Execute( fileInfoRequest.ExecuteAsync, this.CancellationToken, GoogleRequestHelper.Cooldown *Utils.Constants.DownloadThreadsCount); ++this.Progress; this.StatusAccumulator.SuccessItem(); return(fileInfo); } catch (Exception e) { if (this.CancellationToken.IsCancellationRequested) { throw; } this.Log.LogError($"Downloading meta-information for file {file.Name} failed.", e); this.StatusAccumulator.FailureOccurred(); throw; } finally { semaphore.Release(); } }