public async Task Add_AfterDisposeStarts_InvokesActionAfterDisposeCompletes() { bool action1Invoked = false; bool action2Invoked = false; var ready = new ManualResetEventSlim(); var signal = new ManualResetEventSlim(); var disposable = AnonymousDisposable.Create(() => { action1Invoked = true; ready.Set(); signal.Wait(); }); var disposeTask = Task.Run(() => disposable.Dispose()); ready.Wait(); var addTask = Task.Run(() => disposable.Add(() => { action2Invoked = true; })); Assert.False(addTask.Wait(100)); Assert.True(action1Invoked); Assert.False(action2Invoked); signal.Set(); await disposeTask; await addTask; Assert.True(action2Invoked); }
public IExpressStore GetCheckpointStore(string checkPointPath) { if (chain.ConsensusNodes.Count != 1) { throw new ArgumentException("Checkpoint restore is only supported on single node express instances", nameof(chain)); } var node = chain.ConsensusNodes[0]; if (IsRunning(node)) { throw new Exception($"node already running"); } checkPointPath = ResolveCheckpointFileName(checkPointPath); if (!fileSystem.File.Exists(checkPointPath)) { throw new Exception($"Checkpoint {checkPointPath} couldn't be found"); } var checkpointTempPath = fileSystem.GetTempFolder(); var folderCleanup = AnonymousDisposable.Create(() => { if (fileSystem.Directory.Exists(checkpointTempPath)) { fileSystem.Directory.Delete(checkpointTempPath, true); } }); var multiSigAccount = node.Wallet.Accounts.Single(a => a.IsMultiSigContract()); RocksDbStore.RestoreCheckpoint(checkPointPath, checkpointTempPath, chain.Magic, multiSigAccount.ScriptHash); return(new CheckpointStore(RocksDbStore.OpenReadOnly(checkpointTempPath), true, folderCleanup)); }
private static (ILogger, IDisposable) InitializeLogger() { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "log.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); var dispose = new AnonymousDisposable(() => { logfile.Dispose(); logconsole.Dispose(); }); // Rules for mapping loggers to targets config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Error, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; return(NLog.LogManager.GetCurrentClassLogger(), dispose); }
public void Dispose_InvokesAction() { bool actionInvoked = false; var disposable = AnonymousDisposable.Create(() => { actionInvoked = true; }); disposable.Dispose(); Assert.True(actionInvoked); }
public void Dispose_AfterAddingNull_DoesNotThrow() { bool action1Invoked = false; var disposable = AnonymousDisposable.Create(() => { action1Invoked = true; }); disposable.Add(null); disposable.Dispose(); Assert.True(action1Invoked); }
public void MultipleDispose_OnlyInvokesActionOnce() { var counter = 0; var disposable = AnonymousDisposable.Create(() => { ++counter; }); disposable.Dispose(); disposable.Dispose(); Assert.Equal(1, counter); }
public void AnonymousDisposable() { var controller = new Mock <IEventController>(); var disposable = new AnonymousDisposable(() => controller.Object.RaiseEvent("Disposed")); disposable.Dispose(); disposable.Dispose(); disposable.Dispose(); controller.Verify(c => c.RaiseEvent("Disposed"), Times.Once); }
public static IDisposable GetDeleteDirectoryDisposable(string path) { return(AnonymousDisposable.Create(() => { if (Directory.Exists(path)) { Directory.Delete(path, true); } })); }
public void Dispose_AfterAdd_InvokesBothActions() { bool action1Invoked = false; bool action2Invoked = false; var disposable = AnonymousDisposable.Create(() => { action1Invoked = true; }); disposable.Add(() => { action2Invoked = true; }); disposable.Dispose(); Assert.True(action1Invoked); Assert.True(action2Invoked); }
public IDisposable Add(Action action) { if (action == null) { throw new ArgumentNullException("action"); } var disposable = new AnonymousDisposable(action); this.Add(disposable); return(disposable); }
public static IDisposable AddUndo(Action action) { var disposable = (IDisposable)null; if (!IsUndoing) { disposable = new AnonymousDisposable(() => _undos.Remove(action)); _undos.Add(action); } return(disposable ?? new AnonymousDisposable(() => { })); }
public void WhenDisposedTwice_ThenInvokesActionOnce() { var called = 0; using (var disposable = new AnonymousDisposable(() => called++)) { disposable.Dispose(); disposable.Dispose(); } Assert.Equal(1, called); }
/// <summary> /// 代替IDisposable,添加在开始时释放资源的Action。 /// </summary> /// <param name="releaseAction">使用Action释放资源</param> public void AddFirst([NotNull] Action releaseAction) { if (releaseAction == null) { throw new ArgumentNullException(nameof(releaseAction)); } ThrowExceptionIfDisposed(); var disposable = new AnonymousDisposable(releaseAction); lock (_lockObject) { _targetLists.Insert(0, disposable); } }
public async Task AllowsMixedChildren() { bool action1Invoked = false; bool action2Invoked = false; var disposable = CollectionAsyncDisposable.Create( new AnonymousAsyncDisposable(async() => { action1Invoked = true; }), AnonymousDisposable.Create(() => action2Invoked = true).ToAsyncDisposable()); await disposable.DisposeAsync(); Assert.True(action1Invoked); Assert.True(action2Invoked); }
public void when_Dispose_is_called_Action_is_called() { var actionWasCalled = false; var anonymousDisposable = new AnonymousDisposable(() => actionWasCalled = true); Assert.That(actionWasCalled, Is.False); anonymousDisposable.Dispose(); Assert.That(actionWasCalled, Is.True); }
public void RestoreCheckpoint(string checkPointArchive, bool force) { if (chain.ConsensusNodes.Count != 1) { throw new ArgumentException("Checkpoint restore is only supported on single node express instances", nameof(chain)); } checkPointArchive = ResolveCheckpointFileName(checkPointArchive); if (!fileSystem.File.Exists(checkPointArchive)) { throw new Exception($"Checkpoint {checkPointArchive} couldn't be found"); } var node = chain.ConsensusNodes[0]; if (IsNodeRunning(node)) { var scriptHash = node.Wallet.DefaultAccount?.ScriptHash ?? "<unknown>"; throw new InvalidOperationException($"node {scriptHash} currently running"); } var checkpointTempPath = fileSystem.GetTempFolder(); using var folderCleanup = AnonymousDisposable.Create(() => { if (fileSystem.Directory.Exists(checkpointTempPath)) { fileSystem.Directory.Delete(checkpointTempPath, true); } }); var nodePath = fileSystem.GetNodePath(node); if (fileSystem.Directory.Exists(nodePath)) { if (!force) { throw new Exception("You must specify force to restore a checkpoint to an existing blockchain."); } fileSystem.Directory.Delete(nodePath, true); } var wallet = DevWallet.FromExpressWallet(ProtocolSettings, node.Wallet); var multiSigAccount = wallet.GetMultiSigAccounts().Single(); RocksDbUtility.RestoreCheckpoint(checkPointArchive, checkpointTempPath, ProtocolSettings.Network, ProtocolSettings.AddressVersion, multiSigAccount.ScriptHash); fileSystem.Directory.Move(checkpointTempPath, nodePath); }
public void RestoreCheckpoint(string checkPointArchive, bool force) { if (chain.ConsensusNodes.Count != 1) { throw new ArgumentException("Checkpoint restore is only supported on single node express instances", nameof(chain)); } checkPointArchive = ResolveCheckpointFileName(checkPointArchive); if (!fileSystem.File.Exists(checkPointArchive)) { throw new Exception($"Checkpoint {checkPointArchive} couldn't be found"); } var node = chain.ConsensusNodes[0]; if (IsRunning(node)) { var scriptHash = node.Wallet.DefaultAccount?.ScriptHash ?? "<unknown>"; throw new InvalidOperationException($"node {scriptHash} currently running"); } var checkpointTempPath = fileSystem.GetTempFolder(); using var folderCleanup = AnonymousDisposable.Create(() => { if (fileSystem.Directory.Exists(checkpointTempPath)) { fileSystem.Directory.Delete(checkpointTempPath, true); } }); var multiSigAccount = node.Wallet.Accounts.Single(a => a.IsMultiSigContract()); var nodeFolder = fileSystem.GetNodePath(node); if (fileSystem.Directory.Exists(nodeFolder)) { if (force) { fileSystem.Directory.Delete(nodeFolder, true); } else { throw new Exception("You must specify force to restore a checkpoint to an existing blockchain."); } } RocksDbStore.RestoreCheckpoint(checkPointArchive, checkpointTempPath, chain.Magic, multiSigAccount.ScriptHash); fileSystem.Directory.Move(checkpointTempPath, nodeFolder); }
protected ReportViewerViewModel(ILog log, IDispatcherSchedulerProvider scheduler, IStandardDialog standardDialog, TReportViewerService service, IToolBarService toolBarService, HistoryViewModel historyViewModel, BindableCollection <IViewModel> itemsCollection) : base(log, scheduler, standardDialog) { Service = service; ToolBarService = toolBarService; _historyViewModel = historyViewModel; Items = itemsCollection; this.SetupHeader(scheduler, "Viewer"); _historyViewModel.Open += Open; Disposables.Add(AnonymousDisposable.Create(() => _historyViewModel.Open -= Open)); }
public void SetUp() { traceOutput = new StringBuilder(); var itsLogListener = new TraceListener(); Trace.Listeners.Add(itsLogListener); EventHandler<InstrumentationEventArgs> handler = (sender, args) => traceOutput.AppendLine(args.LogEntry.ToString()); Instrumentation.Log.EntryPosted += handler; Log.ResetItsLogCheck(); cleanup = new AnonymousDisposable(() => { Instrumentation.Log.EntryPosted -= handler; Trace.Listeners.Remove(itsLogListener); }); }
public void when_Dispose_is_called_then_added_IDisposable_is_disposed() { var disposables = new CompositeDisposable(); var eventWasFired = false; var disposable = AnonymousDisposable.Create(() => eventWasFired = true); disposables.Add(disposable); Assert.That(eventWasFired, Is.False); disposables.Dispose(); Assert.That(eventWasFired, Is.True); }
public void SetUp() { traceOutput = new StringBuilder(); var itsLogListener = new TraceListener(); Trace.Listeners.Add(itsLogListener); EventHandler <InstrumentationEventArgs> handler = (sender, args) => traceOutput.AppendLine(args.LogEntry.ToString()); Instrumentation.Log.EntryPosted += handler; Log.ResetItsLogCheck(); cleanup = new AnonymousDisposable(() => { Instrumentation.Log.EntryPosted -= handler; Trace.Listeners.Remove(itsLogListener); }); }
public void SetUp() { // make sure the Its.Log TraceListener is not registered foreach (TraceListener listener in Trace.Listeners) { if (listener is Instrumentation.TraceListener) { Trace.Listeners.Remove(listener); break; } } Log.ResetItsLogCheck(); traceOutput = new StringBuilder(); var writer = new StringWriter(traceOutput); var textWriterTraceListener = new TextWriterTraceListener(writer); Trace.Listeners.Add(textWriterTraceListener); cleanup = new AnonymousDisposable(() => Trace.Listeners.Remove(textWriterTraceListener)); }
FromLocalServer <P>(Func <PrintQueue, P> printerFromPrintQueue) where P : class { var server = new LocalPrintServer(); var printQueueCollection = server.GetPrintQueues(); var disposable = new AnonymousDisposable(() => { server.Dispose(); printQueueCollection.Dispose(); }); var queues = printQueueCollection.Cast <PrintQueue>().ToArray(); var defaultIndex = DefaultIndex(queues, server.DefaultPrintQueue); var printers = queues.Select(printerFromPrintQueue).ToArray(); var defaultPrinter = defaultIndex >= 0 ? printers[defaultIndex] : null; return(new PrinterSelector <P>(printers, defaultPrinter, disposable)); }
/// <summary> /// An observable sequence that returns when a dispatcher invokes. /// </summary> /// <param name="that">The framework element.</param> /// <returns>An observable sequence that returns when a dispatcher /// invokes.</returns> public static IObservable <Unit> GetBeginInvoke(this FrameworkElement that) { return(new AnonymousObservable <Unit>( observer => { bool hasDisposed = false; IDisposable dispose = new AnonymousDisposable(() => hasDisposed = true); that.Dispatcher.BeginInvoke( new Action( () => { if (!hasDisposed) { hasDisposed = true; observer.OnNext(new Unit()); observer.OnCompleted(); } })); return dispose; })); }
public WorkspaceViewModel(ILog log, IDispatcherService dispatcherService) : base(log, dispatcherService) { Disposables.Add(AnonymousDisposable.Create(() => DisposablesWasDisposed.SafeInvoke(this))); }
public WorkspaceViewModel(ILog log, IDispatcherSchedulerProvider scheduler, IStandardDialog standardDialog) : base(log, scheduler, standardDialog) { Disposables.Add(AnonymousDisposable.Create(() => DisposablesWasDisposed.SafeInvoke(this))); }
public ViewModel() { _disposables = new List <IDisposable>(); _disposable = new AnonymousDisposable(() => _disposables.ForEach(d => d.Dispose())); }
/// <summary> /// An observable sequence that returns when a dispatcher invokes. /// </summary> /// <param name="that">The framework element.</param> /// <returns>An observable sequence that returns when a dispatcher /// invokes.</returns> public static IObservable<Unit> GetBeginInvoke(this FrameworkElement that) { return new AnonymousObservable<Unit>( observer => { bool hasDisposed = false; IDisposable dispose = new AnonymousDisposable(() => hasDisposed = true); that.Dispatcher.BeginInvoke( new Action( () => { if (!hasDisposed) { hasDisposed = true; observer.OnNext(new Unit()); observer.OnCompleted(); } })); return dispose; }); }
public void Dispose_NullAction_DoesNotThrow() { var disposable = AnonymousDisposable.Create(null); disposable.Dispose(); }
private static async Task <IDisposable> DoLockAsync(SemaphoreSlim @this, CancellationToken cancellationToken) { await @this.WaitAsync(cancellationToken).ConfigureAwait(false); return(AnonymousDisposable.Create(() => @this.Release())); }
/// <summary>Schedules the given action to run asynchronously on the queue after dueTime.</summary> /// <remarks>The function is not guaranteed to run at dueTime as the queue may be busy, it will run when next able.</remarks> /// <param name="dueTime">Delay before running the action</param> /// <param name="action">The function to run</param> /// <returns>A disposable token which you can use to cancel the async action if it has not run yet. /// It is always safe to dispose this token, even if the async action has already run</returns> public virtual IDisposable DispatchAfter(TimeSpan dueTime, Action action) { IDisposable cancel = null; IDisposable timer = null; lock (m_schedulerLock) { if (m_isDisposed) throw new ObjectDisposedException("SerialQueue", "Cannot call DispatchAfter on a disposed queue"); timer = m_threadPool.Schedule(dueTime, () => { lock(m_schedulerLock) { m_timers.Remove(timer); if (cancel == null || m_isDisposed) // we've been canceled OR the queue has been disposed return; // we must call DispatchAsync while still holding m_schedulerLock to prevent a window where we get disposed at this point cancel = DispatchAsync(action); } }); m_timers.Add(timer); } cancel = new AnonymousDisposable(() => { lock (m_schedulerLock) m_timers.Remove(timer); timer.Dispose(); }); return new AnonymousDisposable(() => { lock (m_schedulerLock) { if (cancel != null) { cancel.Dispose(); // this will either cancel the timer or cancel the DispatchAsync depending on which stage it's in cancel = null; } } }); }
public WorkspaceViewModel(ILog log, ISchedulerProvider scheduler, IViewService viewService) : base(log, scheduler, viewService) { Disposables.Add(AnonymousDisposable.Create(() => DisposablesWasDisposed.SafeInvoke(this))); }
/// <summary> /// Synchronously waits on the semaphore, and returns a disposable that releases the semaphore when disposed, thus treating this semaphore as a "multi-lock". /// </summary> /// <param name="this">The semaphore to lock.</param> /// <param name="cancellationToken">The cancellation token used to cancel the wait.</param> public static IDisposable Lock(this SemaphoreSlim @this, CancellationToken cancellationToken) { @this.Wait(cancellationToken); return(AnonymousDisposable.Create(() => @this.Release())); }