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

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

1029 Examples 7

19 View Source File : CelesteNetConnection.cs
License : MIT License
Project Creator : 0x0ade

public void Enqueue(DataType data) {
            lock (QueueLock) {
                int count;
                if (MaxCount > 0 && Interlocked.CompareExchange(ref QueueCount, 0, 0) == MaxCount) {
                    QueueSendNext = (QueueSendNext + 1) % Queue.Length;

                } else if ((count = Interlocked.Increment(ref QueueCount)) > Queue.Length) {
                    count--;
                    int next = QueueSendNext;
                    DataType?[] old = Queue;
                    DataType?[] resized = new DataType?[old.Length * 2];
                    if (next + count <= old.Length) {
                        Array.Copy(old, next, resized, 0, count);
                    } else {
                        Array.Copy(old, next, resized, 0, old.Length - next);
                        Array.Copy(old, 0, resized, old.Length - next, count - next);
                    }
                    Queue = resized;
                    QueueSendNext = 0;
                    QueueAddNext = count;
                }

                Queue[QueueAddNext] = data;
                QueueAddNext = (QueueAddNext + 1) % Queue.Length;

                try {
                    Event.Set();
                } catch (ObjectDisposedException) {
                }
            }
        }

19 View Source File : CelesteNetConnection.cs
License : MIT License
Project Creator : 0x0ade

protected virtual void ThreadLoop() {
            try {
                while (Con.IsAlive) {
                    DedupeTimestamp++;

                    int waited = 0;
                    if (Interlocked.CompareExchange(ref QueueCount, 0, 0) == 0)
                        waited = WaitHandle.WaitAny(EventHandles, 1000);

                    if ((waited == WaitHandle.WaitTimeout || DedupeTimestamp % 10 == 0) && LastSent.Count > 0) {
                        for (int i = Dedupes.Count - 1; i >= 0; --i) {
                            DataDedupe slot = Dedupes[i];
                            if (!slot.Update(DedupeTimestamp)) {
                                Dedupes.RemoveAt(i);
                                if (LastSent.TryGetValue(slot.Type, out Dictionary<uint, DataDedupe>? slotByID)) {
                                    slotByID.Remove(slot.ID);
                                    if (slotByID.Count == 0) {
                                        LastSent.Remove(slot.Type);
                                    }
                                }
                            }
                        }
                    }

                    if (!Con.IsAlive)
                        return;

                    DateTime now = DateTime.UtcNow;

                    while (Interlocked.CompareExchange(ref QueueCount, 0, 0) != 0) {
                        DataType? data;
                        lock (QueueLock) {
                            int next = QueueSendNext;
                            data = Queue[next];
                            Queue[next] = null;
                            QueueSendNext = (next + 1) % Queue.Length;
                            Interlocked.Decrement(ref QueueCount);
                        }

                        if (data == null)
                            continue;

                        if (data is DataInternalDisconnect) {
                            Con.Dispose();
                            return;
                        }

                        if ((data.DataFlags & DataFlags.OnlyLatest) == DataFlags.OnlyLatest) {
                            string type = data.GetTypeID(Con.Data);
                            uint id = data.GetDuplicateFilterID();

                            lock (QueueLock) {
                                int next = QueueSendNext;
                                int count = Interlocked.CompareExchange(ref QueueCount, 0, 0);
                                int length = Queue.Length;
                                for (int ii = 0; ii < count; ii++) {
                                    int i = (next + ii) % length;
                                    DataType? d = Queue[i];
                                    if (d != null && d.GetTypeID(Con.Data) == type && d.GetDuplicateFilterID() == id) {
                                        data = d;
                                        Queue[i] = null;
                                    }
                                }
                            }
                        }

                        if ((data.DataFlags & DataFlags.SkipDuplicate) == DataFlags.SkipDuplicate) {
                            string type = data.GetTypeID(Con.Data);
                            uint id = data.GetDuplicateFilterID();

                            if (!LastSent.TryGetValue(type, out Dictionary<uint, DataDedupe>? slotByID))
                                LastSent[type] = slotByID = new();

                            if (slotByID.TryGetValue(id, out DataDedupe? slot)) {
                                if (slot.Data.ConsideredDuplicate(data))
                                    continue;
                                slot.Data = data;
                                slot.Timestamp = DedupeTimestamp;
                                slot.Iterations = 0;
                            } else {
                                Dedupes.Add(slotByID[id] = new(type, id, data, DedupeTimestamp));
                            }

                        }

                        Con.SendRaw(this, data);

                        if ((data.DataFlags & DataFlags.Update) == DataFlags.Update)
                            LastUpdate = now;
                        else
                            LastNonUpdate = now;
                    }

                    if (Con.SendStringMap) {
                        List<Tuple<string, int>> added = Strings.PromoteRead();
                        if (added.Count > 0) {
                            foreach (Tuple<string, int> mapping in added)
                                Con.SendRaw(this, new DataLowLevelStringMapping {
                                    IsUpdate = SendStringMapUpdate,
                                    StringMap = Strings.Name,
                                    Value = mapping.Item1,
                                    ID = mapping.Item2
                                });
                            if (SendStringMapUpdate)
                                LastUpdate = now;
                            else
                                LastNonUpdate = now;
                        }
                    }

                    if (Con.SendKeepAlive) {
                        if (SendKeepAliveUpdate && (now - LastUpdate).TotalSeconds >= 1D) {
                            Con.SendRaw(this, new DataLowLevelKeepAlive {
                                IsUpdate = true
                            });
                            LastUpdate = now;
                        }
                        if (SendKeepAliveNonUpdate && (now - LastNonUpdate).TotalSeconds >= 1D) {
                            Con.SendRaw(this, new DataLowLevelKeepAlive {
                                IsUpdate = false
                            });
                            LastNonUpdate = now;
                        }
                    }

                    Con.SendRawFlush();

                    lock (QueueLock)
                        if (Interlocked.CompareExchange(ref QueueCount, 0, 0) == 0)
                            Event.Reset();
                }

            } catch (ThreadInterruptedException) {

            } catch (ThreadAbortException) {

            } catch (Exception e) {
                if (!(e is IOException) && !(e is ObjectDisposedException))
                    Logger.Log(LogLevel.CRI, "conqueue", $"Failed sending data:\n{e}");

                Con.Dispose();

            } finally {
                Event.Dispose();
            }
        }

19 View Source File : IssuedToken.cs
License : MIT License
Project Creator : actions

internal bool Authenticated()
        {
            return Interlocked.CompareExchange(ref m_authenticated, 1, 0) == 0;
        }

19 View Source File : VssHttpRetryOptions.cs
License : MIT License
Project Creator : actions

public VssHttpRetryOptions MakeReadonly()
        {
            if (Interlocked.CompareExchange(ref m_isReadOnly, 1, 0) == 0)
            {
                m_retryableStatusCodes = new ReadOnlyCollection<HttpStatusCode>(m_retryableStatusCodes.ToList());
                m_retryFilters = new ReadOnlyCollection<VssHttpRetryableStatusCodeFilter>(m_retryFilters.ToList());
            }
            return this;
        }

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

public static void InitializeGlobalSettingsOnce(CodereplacedysisSettings instance)
		{
			instance.ThrowOnNull(nameof(instance));

			if (Interlocked.CompareExchange(ref _isInitialized, value: INITIALIZED, comparand: NOT_INITIALIZED) == NOT_INITIALIZED)
			{
				_cachedSettings = instance;
			}
		}

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

public static void Initialize(AsyncPackage package, OleMenuCommandService commandService)
		{
			if (Interlocked.CompareExchange(ref _isCommandInitialized, value: INITIALIZED, comparand: NOT_INITIALIZED) == NOT_INITIALIZED)
			{
				Instance = new FixBqlCommand(package, commandService);
			}
		}

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

protected static void InitializeSharedStaticData(object roslynDTO)
		{
			roslynDTO.ThrowOnNull(nameof(roslynDTO));

			if (Interlocked.CompareExchange(ref _areStaticMembersInitialized, value: INITIALIZED, comparand: NOT_INITIALIZED) == NOT_INITIALIZED)
			{
				RoslynDTOType = roslynDTO.GetType();
				var bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;

				DtoFields = RoslynDTOType.GetFields(bindingFlags).ToDictionary(field => field.Name);
				DtoProperties = RoslynDTOType.GetProperties(bindingFlags).ToDictionary(property => property.Name);
			}
		}

public static void Initialize(Shell.AsyncPackage package, Shell.OleMenuCommandService commandService)
		{
			if (Interlocked.CompareExchange(ref _isCommandInitialized, value: INITIALIZED, comparand: NOT_INITIALIZED) == NOT_INITIALIZED)
			{
				Instance = new SuppressDiagnosticInSuppressionFileCommand(package, commandService);
			}
		}

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

public static void Initialize(AsyncPackage package, OleMenuCommandService commandService)
		{
			if (Interlocked.CompareExchange(ref _isCommandInitialized, value: INITIALIZED, comparand: NOT_INITIALIZED) == NOT_INITIALIZED)
			{
				Instance = new FormatBqlCommand(package, commandService);
			}
		}

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

internal static void Initialize(Shell.AsyncPackage package, Shell.OleMenuCommandService oleCommandService)
		{
			if (Interlocked.CompareExchange(ref _isCommandInitialized, value: INITIALIZED, comparand: NOT_INITIALIZED) == NOT_INITIALIZED)
			{
				Instance = new GoToDeclarationOrHandlerCommand(package, oleCommandService);
			}
		}

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

public void Dispose()
		{
			if (Interlocked.CompareExchange(ref _isDisposed, value: Disposed, comparand: NotDisposed) == NotDisposed)
			{
				if (_settingsEvents != null)
					_settingsEvents.CodereplacedysisSettingChanged -= SettingsEvents_CodereplacedysisSettingChanged;

				_memoryMappedFile?.Dispose();
			}
		}

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

public static void Initialize(AsyncPackage package, OleMenuCommandService oleCommandService)
		{
			if (Interlocked.CompareExchange(ref _isCommandInitialized, value: INITIALIZED, comparand: NOT_INITIALIZED) == NOT_INITIALIZED)
			{
				Instance = new OpenCodeMapWindowCommand(package, oleCommandService);
			}
		}

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

private static void SetupSingleton(AreplacedinatorVSPackage package)
        {
            if (package == null)
                return;

            if (Interlocked.CompareExchange(ref _instanceInitialized, INSTANCE_INITIALIZED, INSTANCE_UNINITIALIZED) == INSTANCE_UNINITIALIZED)
            {
                Instance = package;
            }
        }

19 View Source File : ThreadPool.cs
License : MIT License
Project Creator : adrenak

private void ThreadFunc() {
            for (;;) {
                m_semapreplaced.WaitOne();
                int nCurrentPointer, nNextPointer;
                do {
                    nCurrentPointer = m_nGetPointer;
                    nNextPointer = nCurrentPointer + 1;
                    if (nNextPointer == m_taskQueue.Length) {
                        nNextPointer = 0;
                    }
                } while (Interlocked.CompareExchange(ref m_nGetPointer, nNextPointer, nCurrentPointer) != nCurrentPointer);
                TaskInfo task = m_taskQueue[nCurrentPointer];
                if (Interlocked.Decrement(ref m_numTasks) == m_taskQueue.Length - 1) {
                    m_getNotification.Set();
                }
                task.callback(task.args);
            }
        }

19 View Source File : SpinLock.cs
License : The Unlicense
Project Creator : aeroson

public bool TryEnter()
        {
            return Interlocked.CompareExchange(ref owner, 0, -1) == -1;
        }

19 View Source File : SpinLock.cs
License : The Unlicense
Project Creator : aeroson

public void Enter()
        {
            int count = 0;
            while (Interlocked.CompareExchange(ref owner, 0, -1) != -1)
            {
                //Lock is owned by someone else.
                count++;
                WaitBriefly(ref count);
            }
            //It's my lock now!
        }

19 View Source File : ZeroStation.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private bool Close()
        {
            if (Interlocked.CompareExchange(ref _state, StationState.Closing, StationState.Run) == StationState.Run)
            {
                SystemManager.Instance.HeartLeft(StationName, RealName);
                ZeroTrace.SystemLog(StationName, "Closing....");
                RunTaskCancel?.Cancel();
                _waitToken.Wait();
            }
            else
            {
                State = StationState.Closed;
            }
            return true;
        }

19 View Source File : RemoteRecorder.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private bool Close()
        {
            if (Interlocked.CompareExchange(ref _state, StationState.Closing, StationState.Run) != StationState.Run)
                return true;
            RunTaskCancel.Dispose();
            RunTaskCancel = null;
            _waitToken.Wait();
            return true;
        }

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

internal async Task TryResetLimitAsync(DateTimeOffset now)
        {
            if (this.ResetAfter.HasValue)
                this.ResetAfter = this.ResetAfterOffset - now;

            if (this._nextReset == 0)
                return;

            if (this._nextReset > now.UtcTicks)
                return;

            while (Interlocked.CompareExchange(ref this._limitResetting, 1, 0) != 0)
#pragma warning restore 420
                await Task.Yield();

            if (this._nextReset != 0)
            {
                this._remaining = this.Maximum;
                this._nextReset = 0;
            }

            this._limitResetting = 0;
        }

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

private async Task<TaskCompletionSource<bool>> WaitForInitialRateLimit(RateLimitBucket bucket)
        {
            while (!bucket._limitValid)
            {
                if (bucket._limitTesting == 0)
                {
                    if (Interlocked.CompareExchange(ref bucket._limitTesting, 1, 0) == 0)
                    {
                        // if we got here when the first request was just finishing, we must not create the waiter task as it would signel ExecureRequestAsync to bypreplaced rate limiting
                        if (bucket._limitValid)
                            return null;

                        // allow exactly one request to go through without having rate limits available
                        var ratelimitsTcs = new TaskCompletionSource<bool>();
                        bucket._limitTestFinished = ratelimitsTcs.Task;
                        return ratelimitsTcs;
                    }
                }
                // it can take a couple of cycles for the task to be allocated, so wait until it happens or we are no longer probing for the limits
                Task waitTask = null;
                while (bucket._limitTesting != 0 && (waitTask = bucket._limitTestFinished) == null)
                    await Task.Yield();
                if (waitTask != null)
                    await waitTask.ConfigureAwait(false);

                // if the request failed and the response did not have rate limit headers we have allow the next request and wait again, thus this is a loop here
            }
            return null;
        }

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

internal async Task OnHelloAsync(GatewayHello hello)
        {
            this.Logger.LogTrace(LoggerEvents.WebSocketReceive, "Received HELLO (OP10)");

            if (this.SessionLock.Wait(0))
            {
                this.SessionLock.Reset();
                this.GetSocketLock().UnlockAfter(TimeSpan.FromSeconds(5));
            }
            else
            {
                this.Logger.LogWarning(LoggerEvents.SessionUpdate, "Attempt to start a session while another session is active");
                return;
            }

            Interlocked.CompareExchange(ref this._skippedHeartbeats, 0, 0);
            this._heartbeatInterval = hello.HeartbeatInterval;
            this._heartbeatTask = Task.Run(this.HeartbeatLoopAsync, this._cancelToken);

            if (string.IsNullOrEmpty(this._sessionId))
                await this.SendIdentifyAsync(this._status).ConfigureAwait(false);
            else
                await this.SendResumeAsync().ConfigureAwait(false);
        }

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

public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
                {
                    if (Interlocked.CompareExchange(ref _once, 1, 0) == 0)
                    {
                        return this;
                    }
                    return new Error<TValue>.ErrorEnumerator(new InvalidOperationException("Only one IAsyncEnumerator supported"));
                }

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 : 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 : CompletableRedoWhenObserver.cs
License : Apache License 2.0
Project Creator : akarnokd

internal void HandlerNext()
        {
            if (Interlocked.Increment(ref trampoline) == 1)
            {
                do
                {
                    if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
                    {
                        source.Subscribe(this);
                    }
                }
                while (Interlocked.Decrement(ref trampoline) != 0);
            }
        }

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

public void OnCompleted()
            {
                if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
                {
                    other.Dispose();
                    downstream.OnCompleted();
                }
            }

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

public void OnError(Exception error)
            {
                if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
                {
                    other.Dispose();
                    downstream.OnError(error);
                }
            }

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

void OtherCompleted()
            {
                if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
                {
                    DisposableHelper.Dispose(ref upstream);
                    downstream.OnCompleted();
                }
            }

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

void OtherError(Exception error)
            {
                if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
                {
                    DisposableHelper.Dispose(ref upstream);
                    downstream.OnError(error);
                }
            }

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

public void Dispose()
            {
                if (Interlocked.CompareExchange(ref exclude, 1, 0) == 0)
                {
                    DisposableHelper.Dispose(ref upstream);
                    DisposableHelper.Dispose(ref task);
                }
                DisposableHelper.Dispose(ref fallbackObserver);
            }

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

public void OnCompleted()
            {
                if (Interlocked.CompareExchange(ref exclude, 1, 0) == 0)
                {
                    DisposableHelper.Dispose(ref task);

                    downstream.OnCompleted();
                }
            }

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

public void OnError(Exception error)
            {
                if (Interlocked.CompareExchange(ref exclude, 1, 0) == 0)
                {
                    DisposableHelper.Dispose(ref task);

                    downstream.OnError(error);
                }
            }

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

internal void Run()
            {
                if (Interlocked.CompareExchange(ref exclude, 1, 0) == 0)
                {
                    DisposableHelper.Dispose(ref upstream);

                    var c = fallback;

                    if (c == null)
                    {
                        downstream.OnError(new TimeoutException());
                    }
                    else
                    {
                        fallback = null;

                        var inner = new CompletableInnerObserver(downstream);
                        if (Interlocked.CompareExchange(ref fallbackObserver, inner, null) == null)
                        {
                            c.Subscribe(inner);
                        }
                    }
                }
            }

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

void InnerCompleted(int index)
            {
                if (Interlocked.CompareExchange(ref this.index, index, -1) == -1)
                {
                    Volatile.Write(ref observers[index], null);
                    Dispose();
                    downstream.OnCompleted();
                }
            }

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

void InnerError(int index, Exception error)
            {
                if (Interlocked.CompareExchange(ref this.index, index, -1) == -1)
                {
                    Volatile.Write(ref observers[index], null);
                    Dispose();
                    downstream.OnError(error);
                }
            }

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

void Unblock()
        {
            if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
            {
                Signal();
            }
        }

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

void InnerSuccess(int index, T item)
        {
            Volatile.Write(ref observers[index], null);

            if (Volatile.Read(ref winner) == -1 && Interlocked.CompareExchange(ref winner, index, -1) == -1)
            {
                Dispose();
                downstream.OnSuccess(item);
            }
        }

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

void InnerError(int index, Exception ex)
        {
            Volatile.Write(ref observers[index], null);

            if (Volatile.Read(ref winner) == -1 && Interlocked.CompareExchange(ref winner, index, -1) == -1)
            {
                Dispose();
                downstream.OnError(ex);
            }
        }

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

void InnerComplete(int index)
        {
            Volatile.Write(ref observers[index], null);

            if (Volatile.Read(ref winner) == -1 && Interlocked.CompareExchange(ref winner, index, -1) == -1)
            {
                Dispose();
                downstream.OnCompleted();
            }
        }

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

public void OnCompleted()
        {
            if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
            {
                foreach (var inner in Interlocked.Exchange(ref observers, TERMINATED))
                {
                    if (!inner.IsDisposed())
                    {
                        inner.dowstream.OnCompleted();
                    }
                }
                DisposableHelper.WeakDispose(ref upstream);
            }
        }

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

internal override void InnerSuccess(InnerObserver sender, R item)
            {
                Remove(sender);
                if (Volatile.Read(ref wip) == 0 && Interlocked.CompareExchange(ref wip, 1, 0) == 0)
                {
                    downstream.OnNext(item);
                    Interlocked.Decrement(ref active);
                }
                else
                {
                    var q = GetOrCreateQueue();
                    q.Enqueue(item);

                    Interlocked.Decrement(ref active);
                    if (Interlocked.Increment(ref wip) != 1)
                    {
                        return;
                    }
                }

                DrainLoop();
            }

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

internal override void InnerSuccess(InnerObserver sender, R item)
            {
                Remove(sender);
                if (Volatile.Read(ref wip) == 0 && Interlocked.CompareExchange(ref wip, 1, 0) == 0)
                {
                    downstream.OnNext(item);
                    if (Interlocked.Decrement(ref active) != 0)
                    {
                        if (Interlocked.Decrement(ref wip) == 0)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    var q = GetOrCreateQueue();
                    q.Enqueue(item);

                    Interlocked.Decrement(ref active);
                    if (Interlocked.Increment(ref wip) != 1)
                    {
                        return;
                    }
                }

                DrainLoop();
            }

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

internal override void InnerSuccess(InnerObserver sender, T item)
            {
                Remove(sender);
                if (Volatile.Read(ref wip) == 0 && Interlocked.CompareExchange(ref wip, 1, 0) == 0)
                {
                    downstream.OnNext(item);
                    if (Interlocked.Decrement(ref active) != 0)
                    {
                        if (Interlocked.Decrement(ref wip) == 0)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    var q = GetOrCreateQueue();
                    q.Enqueue(item);

                    Interlocked.Decrement(ref active);
                    if (Interlocked.Increment(ref wip) != 1)
                    {
                        return;
                    }
                }

                DrainLoop();
            }

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

internal override void RedoComplete()
            {
                Dispose();
                if (Interlocked.CompareExchange(ref halfSerializer, 1, 0) == 0)
                {
                    downstream.OnCompleted();
                }
            }

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

public void OnSuccess(T item)
            {
                if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
                {
                    other.Dispose();
                    downstream.OnSuccess(item);
                }
            }

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

public void OnSuccess(T item)
            {
                if (Interlocked.CompareExchange(ref exclude, 1, 0) == 0)
                {
                    DisposableHelper.Dispose(ref task);

                    downstream.OnSuccess(item);
                }
            }

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

public IDisposable Subscribe(IObserver<T> observer)
        {
            var ccd = new CacheConsumerDisposable(observer, this, head);
            Add(ccd);
            if (Volatile.Read(ref once) == 0 && Interlocked.CompareExchange(ref once, 1, 0) == 0)
            {
                var d = source.Subscribe(this);
                DisposableHelper.SetOnce(ref upstream, d);
                cancel?.Invoke(this);
            }
            Drain(ccd);
            return ccd;
        }

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

public void InnerNext(InnerObserver<R> sender, R item)
            {
                if (Interlocked.CompareExchange(ref wip, 1, 0) == 0)
                {
                    var q = sender.GetQueue();

                    if (current == sender && (q == null || q.IsEmpty()))
                    {
                        downstream.OnNext(item);
                    }
                    else
                    {
                        if (q == null)
                        {
                            q = sender.CreateQueue(capacityHint);
                        }
                        q.Offer(item);
                    }
                    if (Interlocked.Decrement(ref wip) == 0)
                    {
                        return;
                    }
                }
                else
                {
                    var q = sender.GetOrCreateQueue(capacityHint);
                    q.Offer(item);
                    if (Interlocked.Increment(ref wip) != 1)
                    {
                        return;
                    }
                }

                DrainLoop();
            }

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

public override void OnNext(T value)
            {
                var o = observers;
                var n = o.Length;

                var otherValues = new U[n];

                var found = true;
                for (int i = 0; i < n; i++)
                {
                    InnerObserver inner = Volatile.Read(ref o[i]);
                    if (inner == null)
                    {
                        return;
                    }
                    if (!inner.TryLatest(out otherValues[i]))
                    {
                        found = false;
                        break;
                    }
                }

                if (found)
                {
                    var result = default(R);

                    try
                    {
                        result = mapper(value, otherValues);
                    }
                    catch (Exception ex)
                    {
                        OnError(ex);
                        base.Dispose();
                        return;
                    }

                    if (Interlocked.CompareExchange(ref wip, 1, 0) == 0)
                    {
                        downstream.OnNext(result);
                        if (Interlocked.Decrement(ref wip) != 0)
                        {
                            var ex = ExceptionHelper.Terminate(ref errors);
                            downstream.OnError(ex);
                            base.Dispose();
                        }
                    }
                }
            }

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

public IAsyncEnumerator<TSource> GetAsyncEnumerator(CancellationToken cancellationToken)
        {
            if (Interlocked.CompareExchange(ref _once, 1, 0) == 0)
            {
                cancellationToken.Register(v => {
                    var w = (v as UnicastAsyncEnumerable<TSource>);
                    w._disposed = true;
                }, this);
                return new UnicastEnumerator(this);
            }
            return new Error<TSource>.ErrorEnumerator(new InvalidOperationException("The UnicastAsyncEnumerable has its only allowed consumer already"));
        }

See More Examples