public bool Add(IDisposable d) { if (disposed) { d.Dispose(); return false; } lock (this) { if (!disposed) { var set = this.set; if (set == null) { set = new LinkedList<IDisposable>(); this.set = set; } set.AddLast(d); return true; } } d.Dispose(); return false; }
public bool BeginTransaction () { if (inTransaction) throw new InvalidOperationException ("Already in a transaction"); transactionLock = LockWrite (); try { updatingLock = new FileStream (UpdateDatabaseLockFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { // The database is already being updated. Can't do anything for now. return false; } finally { transactionLock.Dispose (); } // Delete .new files that could have been left by an aborted database update transactionLock = LockRead (); CleanDirectory (rootDirectory); inTransaction = true; foldersToUpdate = new Hashtable (); deletedFiles = new Hashtable (); deletedDirs = new Hashtable (); return true; }
public async void ExpectPolicy() { var address = GetRandomAddress(); _server = WebApp.Start(address, appBuilder => { appBuilder.Use<CrossDomainMiddleware>(new CrossDomainOptions() { CaseSensitive = true }); appBuilder.UseWebApi(_config); }); _client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, address + "/crossdomain.xml"); var httpResponseMessage = await _client.SendAsync(request); HttpContent httpContent = httpResponseMessage.Content; IEnumerable<string> values; httpContent.Headers.TryGetValues("Content-Type", out values); var assert = values as string[] ?? values.ToArray(); assert.Should().NotBeNull(Policy); assert.Should().NotBeNull("text/x-cross-domain-policy"); _server.Dispose(); }
private static void Run() { if (Arguments.NumClients > 1) { AppHost = WebApp.Start<Startup>(Arguments.ControllerUrl); if (!WaitForClientsToConnect()) { SignalPhaseChange(ControllerEvents.Abort); for (int attempts = 0; (ClientsConnected > 0) && (attempts < CrankArguments.ConnectionPollAttempts); attempts++) { Thread.Sleep(CrankArguments.ConnectionPollIntervalMS); } AppHost.Dispose(); return; } } RunConnect(); RunSend(); RunDisconnect(); WaitForLastSamples(); if (AppHost != null) { AppHost.Dispose(); } FlushLog(force:true); }
private void Dispose(IDisposable disposable) { if (disposable != null) { disposable.Dispose(); } }
public static void Dispose(IDisposable disposable) { if (disposable != null) { disposable.Dispose(); } }
/// <summary> /// 释放对象 /// </summary> /// <param name="disposeObject"></param> protected void DisposeIt(IDisposable disposeObject) { if (disposeObject != null) { disposeObject.Dispose(); } }
// :: public static void p_StreamDispose(IDisposable ido) { if (ido != null) { ido.Dispose(); } }
static void DisposeIt(IDisposable d) { if (d != null) { d.Dispose (); } }
static void ListenWithQuery() { Console.WriteLine("----- Listening with Tx-Playback and Rx query -----"); _playback = new Playback(); _playback.AddRealTimeSession(Baseline.SessionName); var received = _playback.GetObservable<KNetEvt_RecvIPV4>(); var x = from window in received.Window(TimeSpan.FromSeconds(1), _playback.Scheduler) from stats in (from packet in window group packet by packet.daddr into g from total in g.Sum(p => p.size) select new { address = new IPAddress(g.Key).ToString(), received = total }) .ToList() select stats.OrderBy(s => s.address); _subscription = x.Subscribe(v => { Console.WriteLine("--- {0} ---", DateTime.Now); foreach (var s in v) Console.WriteLine("{0, -15} {1,-10:n0} ", s.address, s.received); Console.WriteLine(); }); _playback.Start(); Console.ReadLine(); _subscription.Dispose(); }
public void Set(IDisposable disposable) { if (disposable == null) { throw new ArgumentNullException("disposable"); } object originalFieldValue = Interlocked.CompareExchange(ref _disposable, disposable, null); if (originalFieldValue == null) { // this is the first call to Set() and Dispose() hasn't yet been called; do nothing } else if (originalFieldValue == _disposedSentinel) { // Dispose() has already been called, so we need to dispose of the object that was just added disposable.Dispose(); } else { #if !NET35 && !SILVERLIGHT && !NETFX_CORE // Set has been called multiple times, fail Debug.Fail("Multiple calls to Disposer.Set(IDisposable) without calling Disposer.Dispose()"); #endif } }
private static void DisposePage(IDisposable page) { if (page == null) return; page.Dispose(); }
public static IDisposable Combine(IDisposable first, IDisposable second) { if (first == null || second == null) return first ?? second; return new Disposable(() => { try { first.Dispose(); } finally { second.Dispose(); } }); }
private static void Close(IDisposable counter) { if (null != counter) { counter.Dispose(); } }
protected override Task DisposeCoreAsync(bool initialized) { _subscription?.Dispose(); _progressRegistration?.Dispose(); _joinedDataSources?.Dispose(); return(Task.CompletedTask); }
protected override void Unsubscribed() { _timerSubscription?.Dispose(); if (_clock != null) { _clock.PlayState = PlayState.Stop; } }
protected override void Dispose(bool disposing) { if (disposing) { _subscription?.Dispose(); _targetBlock.Complete(); } }
public ValueTask DisposeAsync() { if (!_disposed) { _session?.Dispose(); _disposed = true; } return(default);
public static void DisposeObject(IDisposable disposable) { if (disposable != null) { disposable.Dispose(); disposable = null; } }
public Task StopAsync(CancellationToken cancellationToken) { _logger.LogDebug("Stopping subscription manager"); _subscription?.Dispose(); _logger.LogTrace("Exiting StopAsync"); return(Task.CompletedTask); }
public static void RemoveAndDispose(this MultipleDisposable self, IDisposable target) { if (target == null) return; self.Remove(target); target.Dispose(); }
public static IDisposable Combine(IDisposable disposable1, IDisposable disposable2) { return new Disposable(() => { disposable1.Dispose(); disposable2.Dispose(); }); }
public AsyncSubject <Unit> Vacuum() { // Vacuum is a special snowflake. We want to delete all the expired rows before // actually vacuuming. Unfortunately vacuum can't be run in a transaction so we'll // claim an exclusive lock on the queue, drain it and run the delete first before // running our vacuum op without any transactions. var ret = new AsyncSubject <Unit>(); Task.Run(async() => { IDisposable? @lock = null; try { // NB. While the documentation for SemaphoreSlim (which powers AsyncLock) // doesn't guarantee ordering the actual (current) implementation[1] // uses a linked list to queue incoming requests so by adding ourselves // to the queue first and then sending a no-op to the main queue to // force it to finish up and release the lock we avoid any potential // race condition where the main queue reclaims the lock before we // have had a chance to acquire it. // // 1. http://referencesource.microsoft.com/#mscorlib/system/threading/SemaphoreSlim.cs,d57f52e0341a581f var lockTask = _flushLock.LockAsync(_shouldQuit?.Token ?? CancellationToken.None); _operationQueue.Add(OperationQueueItem.CreateUnit(OperationType.DoNothing)); try { @lock = await lockTask.ConfigureAwait(false); } catch (OperationCanceledException) { } var deleteOp = OperationQueueItem.CreateUnit(OperationType.DeleteExpiredSqliteOperation); _operationQueue.Add(deleteOp); FlushInternal(); await deleteOp.CompletionAsUnit; var vacuumOp = OperationQueueItem.CreateUnit(OperationType.VacuumSqliteOperation); MarshalCompletion(vacuumOp.Completion, _vacuum.Value.PrepareToExecute(), Observable.Return(Unit.Default)); await vacuumOp.CompletionAsUnit; } finally { @lock?.Dispose(); } }) .ToObservable() .ObserveOn(_scheduler) .Multicast(ret) .PermaRef(); return(ret); }
protected override void OnDetaching() { AssociatedObject.LayoutUpdated -= AssociatedObject_LayoutUpdated; AssociatedObject.Loaded -= AssociatedObject_Loaded; _disposableHandle?.Dispose(); base.OnDetaching(); }
private static void TryToDispose(IDisposable disposable) { try { disposable.Dispose(); } catch (Exception e) { Simply.Do.Log(MethodBase.GetCurrentMethod()) .Warn("Error disposing {0}".AsFormat(disposable), e); } }
/// <summary> /// Disposes of the managed resources. /// </summary> /// <param name="disposing">If its getting called by the <see cref="Dispose()"/> method.</param> protected virtual void Dispose(bool disposing) { if (disposing) { _isValid.Dispose(); _message.Dispose(); _cleanup?.Dispose(); } }
public IDisposable Reschedule(IDisposable scheduled, Action action, long firstInMs) { if (scheduled != null) { scheduled.Dispose(); } return Schedule(action, firstInMs); }
private void UnbindTableData() { foreach (var e in viewModel.Entities) { e.OnAction -= OnAction; } disposable?.Dispose(); disposable = null; }
/// <inheritdoc/> protected override void OnDetaching() { base.OnDetaching(); if (AssociatedObject != null) { AssociatedObject.AttachedToVisualTree -= AttachedToVisualTree; } _disposable?.Dispose(); }
public void Add(IDisposable disposable) { if (IsDisposed) { disposable.Dispose(); return; } _disposables.Add(disposable); }
private IDisposable Subscribe() { if (_rillSubscription != null) { throw new InvalidOperationException("Can not subscribe while there is an active subscription."); } return(_rill.Subscribe( ev => _stage.Enqueue(ev), successfulId => { _ackCount = Interlocked.Increment(ref _ackCount); }, failedId => { _nackCount = Interlocked.Increment(ref _nackCount); // ReSharper disable once ConstantConditionalAccessQualifier _rillSubscription?.Dispose(); })); }
/// <summary> /// null safe dispose /// </summary> public static void TryDispose(IDisposable disposable) { if (disposable == null) { return; } disposable.Dispose(); }
protected override void Dispose(bool disposing) { _wrapped.Dispose(); Disposed?.Invoke(this, EventArgs.Empty); _additionalDisposable?.Dispose(); _additionalDisposable = null; base.Dispose(disposing); }
public CancellationToken BeginLoad() { _sourceResult?.Dispose(); _sourceCancellation?.Cancel(); _sourceCancellation = new CancellationTokenSource(); return(Token); }
private static void TryToDispose(IDisposable disposable) { try { disposable.Dispose(); } catch (Exception e) { logger .Warn("Error disposing {0}".AsFormatFor(disposable), e); } }
protected override Task DisposeCoreAsync(bool initialized) { if (initialized) { _subscription?.Dispose(); } return(Task.CompletedTask); }
private async Task SetElementsAsync() { if (_entity == null) { return; } _eventHandle?.Dispose(); _eventHandle = _repository.ChangeToken.RegisterChangeCallback(async x => { await SetElementsAsync(); OnDataChange?.Invoke(this, new EventArgs()); }, null); var parent = default(IParent?); if (_repositoryParentSelector != null) { // a bit weird (see CollectionRelationConfig) if (_repositoryParentSelector.ObjectType == typeof(ValueTuple <IParent?, IEntity>)) { parent = _repositoryParentSelector.Getter.Invoke((_parent, _entity)) as IParent; } else if (_parent != null) { parent = _repositoryParentSelector.Getter.Invoke(_parent) as IParent; } } var entities = await _memoryCache.GetOrCreateAsync(new { _repository, parent }, (entry) => { entry.AddExpirationToken(_repository.ChangeToken); return(_repository.InternalGetAllAsync(parent, Query.Default())); }); _elements = entities .Select(entity => (IElement) new ElementDTO { Id = _idProperty.Getter(entity), Labels = _labelProperties.Select(x => x.StringGetter(entity)) }) .ToList(); }
private void UnSubscribe() { if (!_disposed) { _logger.LogWarning("Stop DiagnosticProcessor Hosted Service."); _disposed = true; _subscriber?.Dispose(); _subscriber = null; } }
public static void Impl(IDisposable disposable, IContext context) { try { disposable.Dispose(); } catch (Exception) { } }
public static void DisposeAlso(this IComponent component, IDisposable disposable) { Contract.Requires<ArgumentNullException>(component != null); Contract.Requires<ArgumentNullException>(disposable != null); component.Disposed += (sender, e) => { disposable.Dispose(); }; }
public Task StopAsync(CancellationToken cancellationToken) { foreach (IDisposable disposable in m_disposables) { disposable.Dispose(); } m_observerLifetime?.Dispose(); return(Task.CompletedTask); }
public void Dispose() { if (_clientPingDisposable is not null) { _clientPingDisposable?.Dispose(); } _websocketParserHandler?.Dispose(); _tcpConnectionService?.Dispose(); }
/// <inheritdoc/> public void Dispose() { while (_objects.TryTake(out T obj)) { IDisposable?disposable = obj as IDisposable; disposable?.Dispose(); } _objectsAvailable.Dispose(); }
public void Set(IDisposable disposable) { _disposable = disposable; // Change the state to the need dispose state and dispose if (Interlocked.Exchange(ref _state, NeedDispose) == NeedDispose) { disposable.Dispose(); } }
/// <inheritdoc/> protected override void Dispose(bool disposing) { if (disposing) { _inner?.Dispose(); _list.Dispose(); } base.Dispose(disposing); }
public void Dispose() { if (this._disposed) { return; } this._disposed = true; _foo?.Dispose(); }
private async Task SetElementsAsync() { if (_editContext == null) { return; } _eventHandle?.Dispose(); _eventHandle = _repository.ChangeToken.RegisterChangeCallback(async x => { await SetElementsAsync(); OnDataChange?.Invoke(this, new EventArgs()); }, null); var parent = default(IParent?); if (_entityAsParent && _editContext.EntityState != EntityState.IsNew) { parent = new ParentEntity(_editContext.Parent, _editContext.Entity, _editContext.RepositoryAlias); } if (_repositoryParentSelector != null && _parent != null) { parent = _repositoryParentSelector.Getter.Invoke(_parent) as IParent; } var entities = await _memoryCache.GetOrCreateAsync(new { _repository, parent }, async (entry) => { entry.AddExpirationToken(_repository.ChangeToken); return(await _repository.GetAllAsync(parent, Query.Default(_editContext.CollectionAlias))); }); _elements = entities .Select(entity => (IElement) new Element { Id = _idProperty.Getter(entity), Labels = _labelProperties.Select(x => x.StringGetter(entity)).ToList() }) .ToList(); }
public CoreViewModel( SettingsService settingsService, GammaService gammaService, HotKeyService hotKeyService, ExternalApplicationService externalApplicationService) { _settingsService = settingsService; _gammaService = gammaService; _hotKeyService = hotKeyService; _externalApplicationService = externalApplicationService; _updateConfigurationTimer = new Timer( TimeSpan.FromMilliseconds(50), UpdateConfiguration ); _updateInstantTimer = new Timer( TimeSpan.FromMilliseconds(50), UpdateInstant ); _updateIsPausedTimer = new Timer( TimeSpan.FromSeconds(1), UpdateIsPaused ); // Cancel 'disable temporarily' when switching to enabled this.Bind(o => o.IsEnabled, (sender, args) => { if (IsEnabled) { _enableAfterDelayRegistration?.Dispose(); } }); // Handle settings changes _settingsService.SettingsSaved += (sender, args) => { Refresh(); RegisterHotKeys(); }; }
public void Dispose() { if (_disposed) { return; } _disposed = true; _watcher?.Dispose(); _watcher = null; }
protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _parentTagBox = Parent as TagsBox; _subscription?.Dispose(); var deleteButton = e.NameScope.Find <Button>("PART_DeleteButton"); if (deleteButton is { })
public void GetResult() { try { _awaiter.GetResult(); } finally { _disposable?.Dispose(); } }
public void Dispose() { if (_disposed) { return; } _disposed = true; _cts.Cancel(); _updateTick?.Dispose(); _connection?.Close(); }
public void AddDisposableOnDestroy(IDisposable disposable) { if (calledDestroy) { disposable.Dispose(); return; } if (disposablesOnDestroy == null) disposablesOnDestroy = new CompositeDisposable(); disposablesOnDestroy.Add(disposable); }
public void Dispose() { try { Item?.Dispose(); } finally { _delegated?.Dispose(); } }
private void OwnerChanged(ILogical?c) { _propertySubscription?.Dispose(); _propertySubscription = null; if (c is TabControl tabControl) { _propertySubscription = tabControl.GetObservable(_ownerProperty) .Subscribe(x => PublishNext(x)); } }
public static void closeQuietly(IDisposable disposable) { try { disposable.Dispose(); } catch (Exception e) { Log.Error(e, "IOException should not have been thrown."); } }
/// <summary> /// /// </summary> /// <param name="dispose"></param> public static void SafeDispose(IDisposable dispose) { try { if (dispose != null) dispose.Dispose(); } catch (Exception excp) { LogFactory.LogException(excp, "Diposing a object"); } }
public void Dispose() { if (_disposed) { return; } _disposed = true; _consumption?.Dispose(); _consumerSubscription?.Dispose(); _connection?.Close(); _updateTick?.Dispose(); }
public static Task CompletesTrackingOperation(this Task task, IDisposable token) { if (token == null) { return task; } return task.SafeContinueWith( t => token.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); }
/// <summary>Closes the Closable quietly.</summary> /// <remarks>Closes the Closable quietly. So no exception will be thrown. Can also safely be called with a null value.</remarks> /// <param name="closeable">the Closeable to close.</param> public static void CloseResource(IDisposable closeable) { if (closeable != null) { try { closeable.Dispose(); } catch (IOException e) { Logger.GetLogger(typeof (IOUtil)).Finest("closeResource failed", e); } } }