System.Threading.Interlocked.Exchange(ref int, int)

Here are the examples of the csharp api System.Threading.Interlocked.Exchange(ref int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

730 Examples 7

19 View Source File : ReplayProcessor.cs
License : Apache License 2.0
Project Creator : akarnokd

public override void AddElement(T element)
            {
                var t = tail;
                var a = t.array;
                var n = a.Length;
                var to = tailOffset;
                if (to == n)
                {
                    var q = new ArrayNode(n);
                    a = q.array;
                    a[0] = element;
                    tailOffset = 1;
                    t.next = q;
                    tail = q;
                }
                else
                {
                    a[to] = element;
                    tailOffset = to + 1;
                }

                Interlocked.Exchange(ref size, size + 1);
            }

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

internal static void RunReplay<T>(T concurrentState, (string, Action<T>)[] operations, int threads, int[] threadIds)
        {
            Exception exception = null;
            var runners = new Thread[threads];
            while (--threads >= 0)
            {
                runners[threads] = new Thread(threadId =>
                {
                    int opId = -1, i = -1, tid = (int)threadId;
                    while ((i = Interlocked.Increment(ref opId)) < operations.Length)
                    {
                        if (threadIds[i] == tid)
                        {
                            try { operations[i].Item2(concurrentState); }
                            catch (Exception e)
                            {
                                if (exception is null)
                                {
                                    exception = e;
                                    Interlocked.Exchange(ref opId, operations.Length);
                                }
                            }
                        }
                    }
                });
            }
            for (int i = 0; i < runners.Length; i++) runners[i].Start(i);
            for (int i = 0; i < runners.Length; i++) runners[i].Join();
            if (exception is not null) throw exception;
        }

19 View Source File : DeferredScalarDisposable.cs
License : Apache License 2.0
Project Creator : akarnokd

public virtual void Clear()
        {
            value = default(T);
            Interlocked.Exchange(ref state, Disposed);
        }

19 View Source File : IOExecutorService.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Shutdown()
        {
            while (Volatile.Read(ref state) == STATE_STARTING) ;
            if (Interlocked.CompareExchange(ref state, STATE_SHUTDOWN, STATE_RUNNING) == STATE_RUNNING)
            {
                cleanupTask.Dispose();
                lock (guard)
                {
                    queue = ShutdownQueue;
                    foreach (var ex in executors)
                    {
                        ex.Shutdown();
                    }
                    executors.Clear();
                }
                Interlocked.Exchange(ref state, STATE_FRESH);
            }
        }

19 View Source File : FlowableProcessorRefCount.cs
License : Apache License 2.0
Project Creator : akarnokd

public void OnComplete()
        {
            if (Interlocked.Exchange(ref count, int.MinValue) != int.MinValue)
            {
                source.OnComplete();
            }
        }

19 View Source File : ObservableSourceConcatMap.cs
License : Apache License 2.0
Project Creator : akarnokd

void Drain()
            {
                if (Interlocked.Increment(ref wip) != 1)
                {
                    return;
                }

                var delayErrors = this.delayErrors;
                var queue = this.queue;

                for (; ;)
                {
                    if (Volatile.Read(ref disposed))
                    {
                        queue.Clear();
                    }
                    else
                    {
                        if (Volatile.Read(ref active) == 0)
                        {
                            if (!delayErrors)
                            {
                                var ex = Volatile.Read(ref errors);
                                if (ex != null)
                                {
                                    Volatile.Write(ref disposed, true);
                                    DisposableHelper.Dispose(ref upstream);
                                    downstream.OnError(ex);
                                    continue;
                                }
                            }

                            var d = Volatile.Read(ref done);

                            var v = default(T);

                            var success = false;
                            try
                            {
                                v = queue.TryPoll(out success);
                            }
                            catch (Exception ex)
                            {
                                DisposableHelper.Dispose(ref upstream);
                                if (delayErrors)
                                {
                                    ExceptionHelper.AddException(ref errors, ex);
                                }
                                else
                                {
                                    Interlocked.CompareExchange(ref errors, ex, null);
                                }

                                ex = ExceptionHelper.Terminate(ref errors);
                                Volatile.Write(ref disposed, true);
                                Volatile.Write(ref done, true);

                                downstream.OnError(ex);
                                continue;
                            }

                            if (d && !success)
                            {
                                Volatile.Write(ref disposed, true);
                                var ex = Volatile.Read(ref errors);
                                if (ex != null)
                                {
                                    downstream.OnError(ex);
                                }
                                else
                                {
                                    downstream.OnCompleted();
                                }
                            } else
                            if (success)
                            {
                                var src = default(IObservableSource<R>);

                                try
                                {
                                    src = RequireNonNullRef(mapper(v), "The mapper returned a null IObservableSource");
                                }
                                catch (Exception ex)
                                {
                                    DisposableHelper.Dispose(ref upstream);
                                    if (delayErrors)
                                    {
                                        ExceptionHelper.AddException(ref errors, ex);
                                    }
                                    else
                                    {
                                        Interlocked.CompareExchange(ref errors, ex, null);
                                    }

                                    ex = ExceptionHelper.Terminate(ref errors);
                                    Volatile.Write(ref disposed, true);
                                    Volatile.Write(ref done, true);

                                    downstream.OnError(ex);
                                    continue;
                                }

                                Interlocked.Exchange(ref active, 1);
                                src.Subscribe(inner);
                            }
                        }
                    }

                    if (Interlocked.Decrement(ref wip) == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : OverlayExtensions.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private static void ZOrderCorrectorOnTick(
            object sender,
            EventArgs e)
        {
            if (Interlocked.CompareExchange(ref isCorrecting, 1, 0) < 1)
            {
                try
                {
                    lock (ZOrderLocker)
                    {
                        foreach (var overlay in ToCorrectOverlays)
                        {
                            if (overlay == null)
                            {
                                continue;
                            }

                            if (overlay is Window window &&
                                window.IsLoaded)
                            {
                                if (!XIVPluginHelper.Instance.IsAvailable)
                                {
                                    overlay.EnsureTopMost();
                                    continue;
                                }

                                if (!overlay.IsOverlaysGameWindow())
                                {
                                    overlay.EnsureTopMost();
                                }
                            }
                        }
                    }
                }
                finally
                {
                    Interlocked.Exchange(ref isCorrecting, 0);
                }
            }
        }

19 View Source File : CompletableMerge.cs
License : Apache License 2.0
Project Creator : akarnokd

internal void SubscribeAll(ICompletableSource[] sources)
            {
                Interlocked.Exchange(ref active, sources.Length);
                foreach (var src in sources)
                {
                    var inner = new MergeInnerObserver(this);
                    if (!Add(inner))
                    {
                        break;
                    }
                    src.Subscribe(inner);
                }
            }

19 View Source File : AsyncQueue.cs
License : Apache License 2.0
Project Creator : apache

public void Dispose()
    {
        lock (_lock)
        {
            if (Interlocked.Exchange(ref _isDisposed, 1) != 0)
                return;

            foreach (var pendingDequeue in _pendingDequeues)
                pendingDequeue.Dispose();

            _pendingDequeues.Clear();
            _queue.Clear();
        }
    }

19 View Source File : CompletableMerge.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void Drain()
            {
                if (delayErrors)
                {
                    var a = Volatile.Read(ref active);
                    var ex = Volatile.Read(ref errors);

                    if (a == 0 && Interlocked.CompareExchange(ref active, -1, 0) == 0)
                    {
                        if (ex != null)
                        {
                            downstream.OnError(ex);
                        }
                        else
                        {
                            downstream.OnCompleted();
                        }
                    }
                }
                else
                {
                    var a = Volatile.Read(ref active);
                    var ex = Volatile.Read(ref errors);

                    if (ex != null)
                    {
                        if (a >= 0 && Interlocked.Exchange(ref active, -1) >= 0)
                        {
                            Dispose();
                            downstream.OnError(ex);
                        }
                    }
                    else
                    {
                        if (a == 0 && Interlocked.CompareExchange(ref active, -1, 0) == 0)
                        {
                            downstream.OnCompleted();
                        }
                    }
                }
            }

19 View Source File : BlockingQueueConsumer.cs
License : Apache License 2.0
Project Creator : akarnokd

internal void Shutdown()
        {
            if (Interlocked.Exchange(ref shutdown, 1) == 0)
            {
                Offer(ShutdownAction);
            }
        }

19 View Source File : FlowableSkipUntil.cs
License : Apache License 2.0
Project Creator : akarnokd

public void OtherSignal()
            {
                Interlocked.Exchange(ref gate, 1);
            }

19 View Source File : SkipUntil.cs
License : Apache License 2.0
Project Creator : akarnokd

private void HandleOther(Task t)
            {
                if (Interlocked.Decrement(ref _disposeOther) != 0)
                {
                    Dispose(_other);
                }
                else
                {
                    if (t.IsCanceled)
                    {
                        Interlocked.CompareExchange(ref _error, new OperationCanceledException(), null);
                        _cancelMain.Cancel();
                        Signal();
                    }
                    else if (t.IsFaulted)
                    {
                        Interlocked.CompareExchange(ref _error, ExceptionHelper.Extract(t.Exception), null);
                        _cancelMain.Cancel();
                        Signal();
                    }
                    else
                    {
                        Interlocked.Exchange(ref _gate, 1);
                        Signal();
                    }

                    if (Interlocked.Increment(ref _disposeOther) == 1)
                    {
                        Dispose(_other);
                    }
                }
            }

19 View Source File : SingleThreadedExecutor.cs
License : Apache License 2.0
Project Creator : akarnokd

internal void Shutdown()
        {
            if (Interlocked.Exchange(ref state, STATE_SHUTDOWN) != STATE_SHUTDOWN)
            {
                runner.Shutdown();
            }
        }

19 View Source File : CooldownAttribute.cs
License : MIT License
Project Creator : Aiko-IT-Systems

internal async Task<bool> DecrementUseAsync()
        {
            await this.UsageSemapreplaced.WaitAsync().ConfigureAwait(false);

            // if we're past reset time...
            var now = DateTimeOffset.UtcNow;
            if (now >= this.ResetsAt)
            {
                // ...do the reset and set a new reset time
                Interlocked.Exchange(ref this._remaining_uses, this.MaxUses);
                this.ResetsAt = now + this.Reset;
            }

            // check if we have any uses left, if we do...
            var success = false;
            if (this.RemainingUses > 0)
            {
                // ...decrement, and return success...
                Interlocked.Decrement(ref this._remaining_uses);
                success = true;
            }

            // ...otherwise just fail
            this.UsageSemapreplaced.Release();
            return success;
        }

19 View Source File : PluginMainWorker.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void BeginOverlaysThread()
        {
            // スペルのスレッドを開始する
            this.refreshSpellOverlaysWorker = new DispatcherTimer(DispatcherPriority.Background)
            {
                Interval = TimeSpan.FromMilliseconds(Settings.Default.RefreshInterval)
            };

            this.refreshSpellOverlaysWorker.Tick += (s, e) =>
            {
                if (Interlocked.CompareExchange(ref this.refreshingSpellsLock, 1, 0) < 1)
                {
                    try
                    {
                        this.RefreshSpellOverlaysCore();
                    }
                    catch (Exception ex)
                    {
                        Logger.Write("refresh spell overlays error:", ex);
                    }
                    finally
                    {
                        Interlocked.Exchange(ref this.refreshingSpellsLock, 0);
                    }
                }
            };

            this.refreshingSpellsLock = 0;
            this.refreshSpellOverlaysWorker.Start();

            // テロップのスレッドを開始する
            this.refreshTickerOverlaysWorker = new DispatcherTimer(DispatcherPriority.Background)
            {
                Interval = TimeSpan.FromMilliseconds(Settings.Default.RefreshInterval)
            };

            this.refreshTickerOverlaysWorker.Tick += (s, e) =>
            {
                if (Interlocked.CompareExchange(ref this.refreshingTickersLock, 1, 0) < 1)
                {
                    try
                    {
                        this.RefreshTickerOverlaysCore();
                    }
                    catch (Exception ex)
                    {
                        Logger.Write("refresh ticker overlays error:", ex);
                    }
                    finally
                    {
                        Interlocked.Exchange(ref this.refreshingTickersLock, 0);
                    }
                }
            };

            this.refreshingTickersLock = 0;
            this.refreshTickerOverlaysWorker.Start();
        }

19 View Source File : ObservableSourceConcatMap.cs
License : Apache License 2.0
Project Creator : akarnokd

void InnerError(Exception ex)
            {
                if (delayErrors)
                {
                    ExceptionHelper.AddException(ref errors, ex);
                }
                else
                {
                    Interlocked.CompareExchange(ref errors, ex, null);
                }

                Interlocked.Exchange(ref active, 0);
                Drain();
            }

19 View Source File : InterlockedFastEvent.cs
License : MIT License
Project Creator : ansel86castro

public void Set()
        {
            Interlocked.Exchange(ref counter, 1);
        }

19 View Source File : SuppressionFileWatcherService.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public void Dispose()
		{
			if (Interlocked.Exchange(ref _instanceDisposed, INSTANCE_DISPOSED) == INSTANCE_UNDISPOSED)
			{			
				_fileSystemWatcher.Dispose();		
			}
		}

19 View Source File : AsyncLock.cs
License : Apache License 2.0
Project Creator : apache

public async ValueTask DisposeAsync()
    {
        lock (_pending)
        {
            if (Interlocked.Exchange(ref _isDisposed, 1) != 0)
                return;

            foreach (var pending in _pending)
                pending.Dispose();

            _pending.Clear();
        }

        await _semapreplacedSlim.WaitAsync().ConfigureAwait(false); //Wait for possible lock-holder to finish

        _semapreplacedSlim.Release();
        _semapreplacedSlim.Dispose();
    }

19 View Source File : FlowableFlatMap.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Cancel()
            {
                if (Interlocked.Exchange(ref cancelled, 1) == 0)
                {
                    upstream.Cancel();
                    CancelAll();
                }
            }

19 View Source File : FlowableProcessorRefCount.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Dispose()
        {
            if (Interlocked.Exchange(ref count, int.MinValue) != int.MinValue) { 
                source.Dispose();
            }
        }

19 View Source File : VSColors.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static bool IsDarkTheme()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (Interlocked.Exchange(ref _serviceInitialized, INITIALIZED) == NOT_INITIALIZED)
            {
                _vsUIShell5 = ServiceProvider.GlobalProvider.GetService(typeof(SVsUIShell)) as IVsUIShell5;
            }

            if (_vsUIShell5 == null)
                return true;

            Color editorBackgroundColor = _vsUIShell5.GetThemedWPFColor(EnvironmentColors.DarkColorKey);

            if (editorBackgroundColor == null)
                return true;

            return editorBackgroundColor.R < RedCriteria ||
                   editorBackgroundColor.G < GreenCriteria ||
                   editorBackgroundColor.B < BlueCriteria;
        }

19 View Source File : FlowableProcessorRefCount.cs
License : Apache License 2.0
Project Creator : akarnokd

public void OnError(Exception cause)
        {
            if (Interlocked.Exchange(ref count, int.MinValue) != int.MinValue)
            {
                source.OnError(cause);
            }
        }

19 View Source File : CompletableRedoWhenObserver.cs
License : Apache License 2.0
Project Creator : akarnokd

internal void HandleSignal(X signal)
        {
            Interlocked.Exchange(ref once, 0);
            terminalSignal.OnNext(signal);
        }

19 View Source File : TestExecutor.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Dispose()
            {
                if (Interlocked.Exchange(ref disposed, 1) == 0)
                {
                    parent.RemoveAll(this);
                }
            }

19 View Source File : ParallelFlowableReduceAll.cs
License : Apache License 2.0
Project Creator : akarnokd

void RailError(Exception cause)
            {
                if (Interlocked.Exchange(ref remaining, 0) > 0)
                {
                    CancelAll();
                    Error(cause);
                }
            }

19 View Source File : MaybeZip.cs
License : Apache License 2.0
Project Creator : akarnokd

void InnerCompleted(int index)
        {
            if (delayErrors)
            {
                hasEmpty = true;
                if (Interlocked.Decrement(ref ready) == 0)
                {
                    Volatile.Write(ref values, null);

                    var ex = error;
                    if (ex != null)
                    {
                        downstream.OnError(ex);
                    }
                    else
                    {
                        downstream.OnCompleted();
                    }
                }
            }
            else
            {
                DisposeAll();
                if (Interlocked.Exchange(ref ready, 0) > 0)
                {
                    Volatile.Write(ref values, null);

                    downstream.OnCompleted();
                }
            }
        }

19 View Source File : InterruptibleAction.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Dispose()
        {
            if (Interlocked.CompareExchange(ref state, Disposed, Fresh) != Fresh)
            {
#if !NETSTANDARD
                Thread r = runner;
                if (r != null && r != Thread.CurrentThread)
                {
                    if (Interlocked.CompareExchange(ref state, Interrupting, Running) == Running)
                    {
                        r.Interrupt();
                        Interlocked.Exchange(ref state, Interrupted);
                    }
                }
                else
                {
                    Interlocked.CompareExchange(ref state, Disposed, Running);
                }
#else
                Interlocked.CompareExchange(ref state, Disposed, Running);
#endif
            }
            Interlocked.Exchange(ref action, null);
            Interlocked.Exchange(ref parent, null)?.DeleteAction(this);
            Interlocked.Exchange(ref resource, null)?.Dispose();
        }

19 View Source File : PXOutliningTagger.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void Dispose()
        {
            if (Interlocked.Exchange(ref _isSubscribed, NOT_SUBSCRIBED) == SUBSCRIBED && ColorizerTagger != null)
            {
                ColorizerTagger.TagsChanged -= OnColorizingTaggerTagsChanged;
                ColorizerTagger = null;
            }

            base.Dispose();
        }

19 View Source File : IOExecutorService.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Start()
        {
            if (Interlocked.CompareExchange(ref state, STATE_STARTING, STATE_FRESH) == STATE_FRESH)
            {
                lock (guard)
                {
                    queue = new ArrayQueue<Entry>();
                }
                cleanupTask = timed.Schedule(Cleanup, TimeSpan.FromMilliseconds(TimeToLive), TimeSpan.FromMilliseconds(TimeToLive));
                Interlocked.Exchange(ref state, STATE_RUNNING);
            }
        }

19 View Source File : MaybeZip.cs
License : Apache License 2.0
Project Creator : akarnokd

void InnerError(int index, Exception ex)
        {
            if (delayErrors)
            {
                ExceptionHelper.AddException(ref error, ex);
                if (Interlocked.Decrement(ref ready) == 0)
                {
                    Volatile.Write(ref values, null);
                    downstream.OnError(error);
                }
            }
            else
            {
                DisposeAll();
                if (Interlocked.Exchange(ref ready, 0) > 0)
                {
                    Volatile.Write(ref values, null);
                    downstream.OnError(ex);
                }
            }
        }

19 View Source File : SetCompositeDisposable.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Dispose()
        {
            if (!IsDisposed)
            {
                Interlocked.Exchange(ref disposed, 1);
                HashSet<IDisposable> s;
                lock (this)
                {
                    s = set;
                    set = null;
                }

                if (s != null)
                {
                    foreach (var d in s)
                    {
                        d.Dispose();
                    }
                }
            }
        }

19 View Source File : WebSocketPlayController.cs
License : MIT License
Project Creator : a1q123456

private async Task PlayRecordFile()
        {
            Interlocked.Exchange(ref _playing, 1);
            var buffer = new byte[512];
            int bytesRead;
            do
            {
                await _playLock.WaitAsync();
                bytesRead = await _recordFile.ReadAsync(buffer);
                await Session.SendRawDataAsync(buffer);
                _playLock.Release();
                if (_playRangeTo < _recordFile.Position && _playRangeTo != -1)
                {
                    break;
                }
            } while (bytesRead != 0);
            Interlocked.Exchange(ref _playing, 0);
        }

19 View Source File : ILTemplate.cs
License : MIT License
Project Creator : AlbertMN

public static void Attach()
    {
        if (Interlocked.Exchange(ref isAttached, 1) == 1)
        {
            return;
        }

        var currentDomain = AppDomain.CurrentDomain;
        currentDomain.replacedemblyResolve += Resolvereplacedembly;
    }

19 View Source File : ObservableSourceConcatMap.cs
License : Apache License 2.0
Project Creator : akarnokd

void InnerCompleted()
            {
                Interlocked.Exchange(ref active, 0);
                Drain();
            }

19 View Source File : MainWorker.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void RestartRefreshViewWorker()
        {
            lock (this)
            {
                this.isRefreshingViewsLock = 0;
                this.isRefreshingSubViewsLock = 0;

                restartDispatcher(
                    ref this.refreshViewWorker,
                    Settings.Instance.UIThreadPriority,
                    TimeSpan.FromMilliseconds(Settings.Instance.OverlayRefreshRate),
                    (x, y) =>
                    {
                        if (Interlocked.CompareExchange(ref this.isRefreshingViewsLock, 1, 0) < 1)
                        {
                            try
                            {
                                if (!ActGlobals.oFormActMain.InitActDone)
                                {
                                    return;
                                }

                                this.UpdateOverlayDataMethod?.Invoke();
                            }
                            finally
                            {
                                Interlocked.Exchange(ref this.isRefreshingViewsLock, 0);
                            }
                        }
                    });

                restartDispatcher(
                    ref this.refreshSubViewWorker,
                    DispatcherPriority.ContextIdle,
                    TimeSpan.FromMilliseconds(Settings.Instance.OverlayRefreshRate * 1.2),
                    (x, y) =>
                    {
                        if (Interlocked.CompareExchange(ref this.isRefreshingSubViewsLock, 1, 0) < 1)
                        {
                            try
                            {
                                if (!ActGlobals.oFormActMain.InitActDone)
                                {
                                    return;
                                }

                                this.UpdateSubOverlayDataMethod?.Invoke();
                            }
                            finally
                            {
                                Interlocked.Exchange(ref this.isRefreshingSubViewsLock, 0);
                            }
                        }
                    });
            }

            void restartDispatcher(
                ref DispatcherTimer timer,
                DispatcherPriority priority,
                TimeSpan interval,
                EventHandler handler)
            {
                if (timer != null)
                {
                    timer.Stop();
                    timer = null;
                }

                timer = new DispatcherTimer(priority)
                {
                    Interval = interval
                };

                timer.Tick += handler;

                timer.Start();
            }
        }

19 View Source File : CompletableFlatMapObservable.cs
License : Apache License 2.0
Project Creator : akarnokd

protected override void Drain()
            {
                var d = done;
                var a = Volatile.Read(ref active);

                if (delayErrors)
                {
                    if (d && a == 0)
                    {
                        if (Interlocked.Exchange(ref active, -1) >= 0)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.Complete();
                            }

                            Volatile.Write(ref disposed, true);
                            DisposableHelper.Dispose(ref upstream);
                        }
                    }
                }
                else
                {
                    var ex = Volatile.Read(ref errors);
                    if (ex != null)
                    {
                        if (Interlocked.Exchange(ref active, -1) >= 0)
                        {
                            downstream.OnError(ex);
                            Dispose();
                        }
                    }
                    else
                    if (d && a == 0)
                    {
                        if (Interlocked.Exchange(ref active, -1) >= 0)
                        {
                            downstream.Complete();
                            Volatile.Write(ref disposed, true);
                            DisposableHelper.Dispose(ref upstream);
                        }
                    }
                }
            }

19 View Source File : AccessTokenManager.cs
License : MIT License
Project Creator : ansel86castro

public void ClearToken()
        {
            Interlocked.Exchange(ref _authenticate, 0);
            Interlocked.Exchange(ref token, null);          
        }

19 View Source File : ConcatMany.cs
License : Apache License 2.0
Project Creator : akarnokd

void Drain()
            {
                if (Interlocked.Increment(ref trampoline) != 1)
                {
                    return;
                }

                for (; ; )
                {
                    if (IsDisposed())
                    {
                        while (queue.TryDequeue(out var _)) ;
                    }
                    else
                    {
                        if (Volatile.Read(ref active) == 0)
                        {
                            var isDone = Volatile.Read(ref done);

                            if (isDone)
                            {
                                var ex = Volatile.Read(ref error);
                                if (ex != null)
                                {
                                    downstream.OnError(ex);
                                    DisposeMain();
                                    continue;
                                }
                            }

                            if (queue.TryDequeue(out var source))
                            {
                                var sad = new SinglereplacedignmentDisposable();
                                if (innerObserver.SetDisposable(sad))
                                {
                                    Interlocked.Exchange(ref active, 1);
                                    sad.Disposable = source.Subscribe(innerObserver);
                                }
                            }
                            else
                            {
                                if (isDone)
                                {
                                    downstream.OnCompleted();
                                    DisposeMain();
                                }
                            }
                        }
                    }

                    if (Interlocked.Decrement(ref trampoline) == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

internal static void Run<T>(T concurrentState, (string, Action<T>)[] operations, int threads, int[] threadIds = null)
        {
            if (threadIds is null) threadIds = DummyArray;
            Exception exception = null;
            var opId = -1;
            var runners = new Thread[threads];
            while (--threads >= 0)
            {
                runners[threads] = new Thread(threadId =>
                {
                    int i, tid = (int)threadId;
                    while ((i = Interlocked.Increment(ref opId)) < operations.Length)
                    {
                        threadIds[i] = tid;
                        try { operations[i].Item2(concurrentState); }
                        catch (Exception e)
                        {
                            if (exception is null)
                            {
                                exception = e;
                                Interlocked.Exchange(ref opId, operations.Length);
                            }
                        }
                    }
                });
            }
            for (int i = 0; i < runners.Length; i++) runners[i].Start(i);
            for (int i = 0; i < runners.Length; i++) runners[i].Join();
            if (exception is not null) throw exception;
        }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static void SetPropertyOrFieldValue(this Type enreplacedyType, object enreplacedy, string propertyName, object value)
    {
        if (enreplacedy == null) return;
        if (enreplacedyType == null) enreplacedyType = enreplacedy.GetType();

        if (SetSetPropertyOrFieldValueSupportExpressionTreeFlag == 0)
        {
            if (GetPropertiesDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var prop))
            {
                prop.SetValue(enreplacedy, value, null);
                return;
            }
            if (GetFieldsDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var field))
            {
                field.SetValue(enreplacedy, value);
                return;
            }
            throw new Exception($"The property({propertyName}) was not found in the type({enreplacedyType.DisplayCsharp()})");
        }

        Action<object, string, object> func = null;
        try
        {
            func = _dicSetPropertyOrFieldValue
                .GetOrAdd(enreplacedyType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
                .GetOrAdd(propertyName, pn =>
                {
                    var t = enreplacedyType;
                    MemberInfo memberinfo = enreplacedyType.GetPropertyOrFieldIgnoreCase(pn);
                    var parm1 = Expression.Parameter(typeof(object));
                    var parm2 = Expression.Parameter(typeof(string));
                    var parm3 = Expression.Parameter(typeof(object));
                    var var1Parm = Expression.Variable(t);
                    var exps = new List<Expression>(new Expression[] {
                            Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
                    });
                    if (memberinfo != null)
                    {
                        exps.Add(
                            Expression.replacedign(
                                Expression.MakeMemberAccess(var1Parm, memberinfo),
                                Expression.Convert(
                                    parm3,
                                    memberinfo.GetPropertyOrFieldType()
                                )
                            )
                        );
                    }
                    return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
                });
        }
        catch
        {
            System.Threading.Interlocked.Exchange(ref SetSetPropertyOrFieldValueSupportExpressionTreeFlag, 0);
            SetPropertyOrFieldValue(enreplacedyType, enreplacedy, propertyName, value);
            return;
        }
        func(enreplacedy, propertyName, value);
    }

19 View Source File : AtomicBool.cs
License : Apache License 2.0
Project Creator : apache

public void Set(bool newValue)
        {
            Interlocked.Exchange(ref value, newValue ? 1 : 0);
        }

19 View Source File : DeferredScalarDisposable.cs
License : Apache License 2.0
Project Creator : akarnokd

public virtual void Dispose()
        {
            Interlocked.Exchange(ref state, Disposed);
        }

19 View Source File : CompletableMerge.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void Drain()
            {
                if (delayErrors)
                {
                    var a = Volatile.Read(ref active);
                    var ex = Volatile.Read(ref errors);

                    if (a == 0 && Interlocked.CompareExchange(ref active, -1, 0) == 0)
                    {
                        if (ex != null)
                        {
                            downstream.OnError(ex);
                        }
                        else
                        {
                            downstream.OnCompleted();
                        }
                    }
                }
                else
                {
                    var a = Volatile.Read(ref active);
                    var ex = Volatile.Read(ref errors);

                    if (ex != null)
                    {
                        if (a != -1 && Interlocked.Exchange(ref active, -1) != -1)
                        {
                            Dispose();
                            downstream.OnError(ex);
                        }
                    }
                    else
                    {
                        if (a == 0 && Interlocked.CompareExchange(ref active, -1, 0) == 0)
                        {
                            downstream.OnCompleted();
                        }
                    }
                }
            }

19 View Source File : IdleBus`1.cs
License : MIT License
Project Creator : 2881099

bool InternalRemove(TKey key, bool isNow, bool isThrow)
        {
            if (isdisposed) throw new Exception($"{key} 删除失败 ,{nameof(IdleBus<TValue>)} 对象已释放");
            if (_dic.TryRemove(key, out var item) == false)
            {
                var error = new Exception($"{key} 删除失败 ,因为没有注册");
                this.OnNotice(new NoticeEventArgs(NoticeType.Remove, key, error, error.Message));
                if (isThrow) throw error;
                return false;
            }

            Interlocked.Exchange(ref item.releaseErrorCounter, 0);
            if (isNow)
            {
                item.Release(() => true);
                this.OnNotice(new NoticeEventArgs(NoticeType.Remove, item.key, null, $"{key} 删除成功,{_usageQuanreplacedy}/{Quanreplacedy}"));
                return true;
            }

            item.lastActiveTime = DateTime.Now;
            if (item.value == null) item.lastActiveTime = DateTime.Now.Subtract(item.idle).AddSeconds(-60); //延时删除
            _removePending.TryAdd(Guid.NewGuid().ToString(), item);
            this.OnNotice(new NoticeEventArgs(NoticeType.Remove, item.key, null, $"{key} 删除成功,并且已标记为延时释放,{_usageQuanreplacedy}/{Quanreplacedy}"));
            return true;
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

private async Task SeekAndPlay(double milliSeconds, CancellationToken ct)
        {
            await _playLock.WaitAsync();
            Interlocked.Exchange(ref _playing, 1);
            try
            {

                _recordFile.Seek(9, SeekOrigin.Begin);
                FlvDemuxer.SeekNoLock(milliSeconds, _metaData == null ? null : _metaData.Data[2] as Dictionary<string, object>, ct);
                await StartPlayNoLock(ct);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Interlocked.Exchange(ref _playing, 0);
                _playLock.Release();
            }
        }

19 View Source File : PXOutliningTagger.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void SubscribeToColorizingTaggerEvents(PXColorizerTaggerBase colorizerTagger)
        {
            if (colorizerTagger.TaggerType == TaggerType.RegEx)
                return;

            if (Interlocked.Exchange(ref _isSubscribed, SUBSCRIBED) == NOT_SUBSCRIBED)
            {
                ColorizerTagger = colorizerTagger;
                ColorizerTagger.TagsChanged += OnColorizingTaggerTagsChanged;
            }
        }

19 View Source File : CompletableUnsubscribeOn.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Dispose()
            {
                if (Interlocked.Exchange(ref disposed, 1) == 0)
                {
                    scheduler.Schedule(this, RUN);
                }
            }

19 View Source File : BooleanSubscription.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Cancel()
        {
            Interlocked.Exchange(ref cancelled, 1);
        }

See More Examples