Пример #1
0
 public void LogRemainingOperations()
 {
     Interlocked.MemoryBarrier();
     if (NetEventSource.IsEnabled)
     {
         NetEventSource.Info(this, $"Releasing with pending operations: {_refCount}");
     }
 }
Пример #2
0
        void MemoryBarrier()
        {
#if NETFX_CORE
            Interlocked.MemoryBarrier();
#else
            Thread.MemoryBarrier();
#endif
        }
Пример #3
0
        public static void MemoryBarrier()
        {
#if NETCOREAPP1_1
            Interlocked.MemoryBarrier();
#else
            Thread.MemoryBarrier();
#endif
        }
Пример #4
0
        public static void MemoryBarrier()
        {
#if NETFX_CORE || NET_4_6
            Interlocked.MemoryBarrier();
#else
            Thread.MemoryBarrier();
#endif
        }
Пример #5
0
 public void LogRemainingOperations()
 {
     Interlocked.MemoryBarrier();
     if (GlobalLog.IsEnabled)
     {
         GlobalLog.Print("InnerSafeCloseSocket: Releasing with pending operations: " + _refCount);
     }
 }
Пример #6
0
        public static void MemoryBarrier()
        {
#if (LESSTHAN_NETCOREAPP20 || TARGETS_NETSTANDARD) && !PROFILE328
            Interlocked.MemoryBarrier();
#else
            Thread.MemoryBarrier();
#endif
        }
Пример #7
0
 public ushort GrantClassID()
 {
     Interlocked.MemoryBarrier();
     lock (_guarder.TokenInterlockerGuard)
     {
         return(Increment(ref _vault.LastClassID));
     }
 }
Пример #8
0
Файл: Memory.cs Проект: yvvan/rd
        public static void Barrier()
        {
#if (NET35)
            Thread.MemoryBarrier();
#else
            Interlocked.MemoryBarrier();
#endif
        }
Пример #9
0
        public TItem Wait(CancellationToken cancellationToken)
        {
            using (var compositeCancellation = CancellationTokenSource
                                               .CreateLinkedTokenSource(_disposeCancellation, cancellationToken))
            {
                while (true)
                {
                    if (_disposeCancellation.IsCancellationRequested)
                    {
                        throw new ObjectDisposedException(GetType().Name);
                    }

                    Interlocked.MemoryBarrier();
                    Interlocked.Increment(ref _readersCount);
                    Interlocked.MemoryBarrier();

                    try
                    {
                        try
                        {
                            _readSem.Wait(compositeCancellation.Token);
                        }
                        catch (OperationCanceledException)
                        {
                            if (_disposeCancellation.IsCancellationRequested)
                            {
                                throw new ObjectDisposedException(GetType().Name);
                            }

                            throw;
                        }


                        QueueItem qitem;
                        if (!_queue.TryDequeue(out qitem))
                        {
                            continue;
                        }

                        qitem.DisableCancellation();

                        var item = qitem.Value;
                        if (item.Cancellation.IsCancellationRequested)
                        {
                            item.TrySetCanceled(item.Cancellation);
                            continue;
                        }

                        return(item);
                    }
                    finally
                    {
                        Interlocked.MemoryBarrier();
                        Interlocked.Decrement(ref _readersCount);
                    }
                }
            }
        }
Пример #10
0
        private void ThreadExecutor()
        {
            Interlocked.MemoryBarrier();

            Window.MakeCurrent();

            //Fired when the window resizes
            Window.Resize += (sender, e) =>
            {
                GL.Viewport(Window.Size);
                EventDispatcher.FireEvent(new WindowResizeEvent(Window.Size.Width, Window.Size.Height));
            };

            //Fired when the window is moved
            Window.Move += (sender, e) => EventDispatcher.FireEvent(new WindowMovedEvent(Window.Location.X, Window.Location.Y));

            //Key events
            Window.KeyPress += (sender, e) => EventDispatcher.FireEvent(new KeyPressedEvent(e));
            Window.KeyDown  += (sender, e) => EventDispatcher.FireEvent(new KeyDownEvent(e));
            Window.KeyUp    += (sender, e) => EventDispatcher.FireEvent(new KeyUpEvent(e));

            //Mouse events
            Window.MouseEnter += (sender, e) => EventDispatcher.FireEvent(new MouseEnterEvent());
            Window.MouseLeave += (sender, e) => EventDispatcher.FireEvent(new MouseLeaveEvent());
            Window.MouseDown  += (sender, e) => EventDispatcher.FireEvent(new MouseDownEvent(e));
            Window.MouseUp    += (sender, e) => EventDispatcher.FireEvent(new MouseUpEvent(e));
            Window.MouseWheel += (sender, e) => EventDispatcher.FireEvent(new MouseWheelEvent(e));
            Window.MouseMove  += (sender, e) => EventDispatcher.FireEvent(new MouseMoveEvent(e));

            while (!TerminateFlag)
            {
                Event.WaitOne(THREAD_WAIT);

                ConcurrentQueue <Action> Frame;

                if (FrameQueue.TryDequeue(out Frame))
                {
                    while (FrameQueue.TryDequeue(out Frame))
                    {
                        ;
                    }

                    Action Act;
                    while (Frame.TryDequeue(out Act))
                    {
                        Act();
                    }

                    Action <GameWindow> WindowTask;
                    while (WindowTasks.TryDequeue(out WindowTask))
                    {
                        WindowTask(Window);
                    }
                    Window.SwapBuffers();
                    Window.ProcessEvents();
                }
            }
        }
Пример #11
0
        private void ChangeState(CacheEvent @event, T value = default)
        {
            switch (@event)
            {
            case CacheEvent.Load:
                if (StateChange(CacheState.Pending, CacheState.Loading))
                {
                    this.Load();
                }
                break;

            case CacheEvent.Expire:
                if (StateChange(CacheState.Active, CacheState.Reloading))
                {
                    Task.Run(async() =>
                    {
                        try
                        {
                            await this.Load();
                        }
                        catch (Exception)
                        {
                        }
                    });
                }
                break;

            case CacheEvent.Error:
                // TODO figure out what to do on an error.
                Volatile.Write(ref _currentState, 0);
                break;

            case CacheEvent.Loaded:
                if (StateChange(CacheState.Loading, CacheState.Loaded))
                {
                    Volatile.Write(ref _value, value);
                    Interlocked.MemoryBarrier();     // Need this here to prevent read/write reordering. (LoadStore barrier)
                    Volatile.Write(ref _currentState, (int)CacheState.Active);
                    _stopWatchThreadSafe.Reset();
                    lock (_lock)
                    {
                        foreach (var pendingTask in _pendingTasks)
                        {
                            pendingTask.SetResult(value);
                        }
                        _pendingTasks = new List <TaskCompletionSource <T> >(0);
                    }
                }
                else if (Volatile.Read(ref _currentState) == (int)CacheState.Reloading)
                {
                    // Don't need any ordering here.
                    Volatile.Write(ref _value, value);
                    Volatile.Write(ref _currentState, (int)CacheState.Active);
                    _stopWatchThreadSafe.Reset();
                }
                break;
            }
        }
Пример #12
0
        /// <summary>
        /// It callbacks all operations already sent / or to be written, that do not have a response.
        /// Invoked from an IO Thread or a pool thread
        /// </summary>
        internal void CancelPending(Exception ex, SocketError?socketError = null)
        {
            _isCanceled = true;
            var wasClosed = Interlocked.Exchange(ref _writeState, Connection.WriteStateClosed) == Connection.WriteStateClosed;

            if (!wasClosed)
            {
                if (Closing != null)
                {
                    Closing(this);
                }

                Connection.Logger.Info("Cancelling in Connection {0}, {1} pending operations and write queue {2}", Address,
                                       InFlight, _writeQueue.Count);

                if (socketError != null)
                {
                    Connection.Logger.Verbose("The socket status received was {0}", socketError.Value);
                }
            }
            if (ex == null || ex is ObjectDisposedException)
            {
                if (socketError != null)
                {
                    ex = new SocketException((int)socketError.Value);
                }
                else
                {
                    //It is closing
                    ex = new SocketException((int)SocketError.NotConnected);
                }
            }
            // Dequeue all the items in the write queue
            var            ops = new LinkedList <OperationState>();
            OperationState state;

            while (_writeQueue.TryDequeue(out state))
            {
                ops.AddLast(state);
            }
            // Remove every pending operation
            while (!_pendingOperations.IsEmpty)
            {
                Interlocked.MemoryBarrier();
                // Remove using a snapshot of the keys
                var keys = _pendingOperations.Keys.ToArray();
                foreach (var key in keys)
                {
                    if (_pendingOperations.TryRemove(key, out state))
                    {
                        ops.AddLast(state);
                    }
                }
            }
            Interlocked.MemoryBarrier();
            OperationState.CallbackMultiple(ops, ex);
            Interlocked.Exchange(ref _inFlight, 0);
        }
Пример #13
0
            /// <summary>Tries to peek at an element from the queue, without removing it.</summary>
            public bool TryPeek(out T result, bool resultUsed)
            {
                if (resultUsed)
                {
                    // In order to ensure we don't get a torn read on the value, we mark the segment
                    // as preserving for observation.  Additional items can still be enqueued to this
                    // segment, but no space will be freed during dequeues, such that the segment will
                    // no longer be reusable.
                    _preservedForObservation = true;
                    Interlocked.MemoryBarrier();
                }

                // Loop in case of contention...
                var spinner = new SpinWait();

                while (true)
                {
                    // Get the head at which to try to peek.
                    int currentHead = Volatile.Read(ref _headAndTail.Head);
                    int slotsIndex  = currentHead & _slotsMask;

                    // Read the sequence number for the head position.
                    int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber);

                    // We can peek from this slot if it's been filled by an enqueuer, which
                    // would have left the sequence number at pos+1.
                    int diff = sequenceNumber - (currentHead + 1);
                    if (diff == 0)
                    {
                        result = resultUsed ? _slots[slotsIndex].Item : default(T);
                        return(true);
                    }
                    else if (diff < 0)
                    {
                        // The sequence number was less than what we needed, which means this slot doesn't
                        // yet contain a value we can peek, i.e. the segment is empty.  Technically it's
                        // possible that multiple enqueuers could have written concurrently, with those
                        // getting later slots actually finishing first, so there could be elements after
                        // this one that are available, but we need to peek in order.  So before declaring
                        // failure and that the segment is empty, we check the tail to see if we're actually
                        // empty or if we're just waiting for items in flight or after this one to become available.
                        bool frozen      = _frozenForEnqueues;
                        int  currentTail = Volatile.Read(ref _headAndTail.Tail);
                        if (currentTail - currentHead <= 0 || (frozen && (currentTail - FreezeOffset - currentHead <= 0)))
                        {
                            result = default(T);
                            return(false);
                        }

                        // It's possible it could have become frozen after we checked _frozenForEnqueues
                        // and before reading the tail.  That's ok: in that rare race condition, we just
                        // loop around again.
                    }

                    // Lost a race. Spin a bit, then try again.
                    spinner.SpinOnce();
                }
            }
Пример #14
0
        // Called by the runtime when it finds a class whose static class constructor has probably not run
        // (probably because it checks in the initialized flag without thread synchronization).
        //
        // This method should synchronize with other threads, recheck the initialized flag and execute the
        // cctor method (whose address is given in the context structure) before setting the initialized flag
        // to 1. Once in this state the runtime will not call this method again for the same type (barring
        // race conditions).
        //
        // The context structure passed by reference lives in the image of one of the application's modules.
        // The contents are thus fixed (do not require pinning) and the address can be used as a unique
        // identifier for the context.
        private static unsafe void CheckStaticClassConstruction(ref StaticClassConstructionContext context)
        {
            // This is a simplistic placeholder implementation. For instance it uses a busy wait spinlock and
            // does not handle recursion.

            while (true)
            {
                // Read the current state of the cctor.
                int oldInitializationState = context.initialized;

                // Once it transitions to 1 then the cctor has been run (another thread got there first) and
                // we can simply return.
                if (oldInitializationState == 1)
                {
                    return;
                }

                // If the state is anything other than 0 (the initial state) then another thread is currently
                // running this cctor. We must wait for it to complete doing so before continuing, so loop
                // again.
                if (oldInitializationState != 0)
                {
                    continue;
                }

                // C# warns that passing a volatile field to a method via a reference loses the volatility of the field.
                // However the method in question is Interlocked.CompareExchange so the volatility in this case is
                // unimportant.
#pragma warning disable 420

                // We read a state of 0 (the initial state: not initialized and not being initialized). Try to
                // transition this to 2 which will let other threads know we're going to run the cctor here.
                if (Interlocked.CompareExchange(ref context.initialized, 2, 0) == 0)
                {
                    // We won the race to transition the state from 0 -> 2. So we can now run the cctor. Other
                    // threads trying to do the same thing will spin waiting for us to transition the state to
                    // 1.

                    // Call the cctor code directly from the address in the context. The <int> here says the
                    // cctor returns an int because the calli transform used doesn't handle the void case yet.
                    Call <int>(context.cctorMethodAddress);

                    // Insert a memory barrier here to order any writes executed as part of static class
                    // construction above with respect to the initialized flag update we're about to make
                    // below. This is important since the fast path for checking the cctor uses a normal read
                    // and doesn't come here so without the barrier it could observe initialized == 1 but
                    // still see uninitialized static fields on the class.
                    Interlocked.MemoryBarrier();

                    // Set the state to 1 to indicate to the runtime and other threads that this cctor has now
                    // been run.
                    context.initialized = 1;
                }

                // If we get here some other thread changed the initialization state to a non-zero value
                // before we could. Loop at try again.
            }
        }
Пример #15
0
            /// <summary>
            /// Read the value applying full fence semantic
            /// </summary>
            /// <returns>The current value</returns>
            public long ReadFullFence()
            {
#if NETFX_CORE
                Interlocked.MemoryBarrier();
#else
                Thread.MemoryBarrier();
#endif
                return(_value);
            }
Пример #16
0
 private void Leave()
 {
     Interlocked.Decrement(ref counter);
     Interlocked.MemoryBarrier(); // is this needed?
     if (isShutdown)
     {
         tcs.TrySetResult(null);
     }
 }
Пример #17
0
 /// <summary>
 /// Dispose.
 /// </summary>
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         _disposed = true;
         Interlocked.MemoryBarrier();
         GrammarApi.sol_DeleteSentenceBroker(_hObject);
     }
 }
        internal void Freeze()
        {
            Debug.Assert(!_frozen);

            // make sure that values from all threads are visible:
            Interlocked.MemoryBarrier();

            _frozen = true;
        }
Пример #19
0
            /// <summary>
            /// Write the value applying full fence semantic
            /// </summary>
            /// <param name="newValue">The new value</param>
            public void WriteFullFence(long newValue)
            {
#if NETFX_CORE
                Interlocked.MemoryBarrier();
#else
                Thread.MemoryBarrier();
#endif
                _value = newValue;
            }
Пример #20
0
 public void Clear()
 {
     lock (sync)
     {
         var newTable = CreateInitialTable();
         Interlocked.MemoryBarrier();
         table = newTable;
     }
 }
Пример #21
0
        public async Task <IDisposable> LockAsync(CancellationToken cancellationToken)
        {
            await _sem.WaitAsync(cancellationToken)
            .ConfigureAwait(false);

            Interlocked.MemoryBarrier();

            return(GetUnlockingDisposable());
        }
Пример #22
0
 private void SaveResumeDataFailedAlert(Core.save_resume_data_failed_alert a)
 {
     Interlocked.MemoryBarrier();
     Interlocked.Decrement(ref outstanding_resume_data);
     if (outstanding_resume_data == 0 && no_more_resume)
     {
         no_more_data.Set();
     }
 }
Пример #23
0
 private void ConnectionChanged(ConnectionStatus status)
 {
     Interlocked.MemoryBarrier();
     if ((status.HasFlag(ConnectionStatus.Disconnected) ||
          status.HasFlag(ConnectionStatus.Offline)) && _start && _borg != null)
     {
         _resetEvent.Set();
     }
 }
Пример #24
0
            private void ImportDataMembers()
            {
                /*
                 * DataMembers are used for the deserialization of Exceptions.
                 * DataMembers represent the fields and/or settable properties that the underlying Exception has.
                 * The DataMembers are stored and eventually passed to a ClassDataContract created from the underlying Exception.
                 * The ClassDataContract uses the list of DataMembers to set the fields/properties for the newly created Exception.
                 * If a DataMember is a property it must be settable.
                 */

                Type type = this.UnderlyingType;

                if (type == Globals.TypeOfException)
                {
                    ImportSystemExceptionDataMembers(); //System.Exception must be handled specially because it is the only exception that imports private fields.
                    return;
                }

                List <DataMember> tempMembers;

                if (BaseContract != null)
                {
                    tempMembers = new List <DataMember>(BaseContract.Members);  //Don't set tempMembers = BaseContract.Members and then start adding, because this alters the base's reference.
                }
                else
                {
                    tempMembers = new List <DataMember>();
                }
                Dictionary <string, DataMember> memberNamesTable = new Dictionary <string, DataMember>();

                MemberInfo[] memberInfos;
                memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);

                for (int i = 0; i < memberInfos.Length; i++)
                {
                    MemberInfo member = memberInfos[i];

                    //Public properties with set methods can be deserialized with the ClassDataContract
                    PropertyInfo publicProperty = member as PropertyInfo;
                    if (publicProperty != null && publicProperty.SetMethod != null)
                    {
                        DataMember memberContract = new DataMember(member);

                        memberContract.Name       = DataContract.EncodeLocalName(member.Name);
                        memberContract.IsRequired = false;
                        memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
                        if (HasNoConflictWithBaseMembers(memberContract))
                        {
                            CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
                        }
                    }
                }

                Interlocked.MemoryBarrier();
                _members = tempMembers;
            }
Пример #25
0
        public ValueTask <bool> MoveNextAsync()
        {
            if (this._isAwaiting != 0)
            {
                throw new InvalidOperationException("The previous task has not been completed.");
            }

            this._taskHelper.Reset();

            this._isAwaiting = 1;
            Interlocked.MemoryBarrier();

            if (this._cancellationToken.IsCancellationRequested)
            {
                if (this.WriteResult())
                {
                    this._taskHelper.SetResult(null);
                }
            }
            else if (this._isCompleted)
            {
                if (this.WriteResult())
                {
                    this._taskHelper.SetResult(false);
                }
            }
            else
            {
                Request();
            }

            return(new ValueTask <bool>(this, this._taskHelper.Version));

            async void Request()
            {
                try
                {
                    var subscription = await this._subscription.Task.ConfigureAwait(false);

                    lock (this.SubscriptionLock)
                    {
                        if (!this._isCompleted)
                        {
                            subscription.Request(1);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (this.WriteResult())
                    {
                        this._taskHelper.SetException(ex);
                    }
                }
            }
        }
            private void FlushInternal(int count)
            {
                _count = count;
                _queue._currentBatch = new Batch(_queue);

                //	The full fence ensures that the current batch will never be added to the queue before _count is set.
                Interlocked.MemoryBarrier();

                _queue._batchQueue.Add(this);
            }
Пример #27
0
 public void SetComplete()
 {
     if (_isComplete)
     {
         return;
     }
     _isComplete = true;
     Interlocked.MemoryBarrier();
     _waitHandle.Set();
 }
Пример #28
0
        protected override void OnStart(string[] args)
        {
            //OnStart shoud return right away, otherwise SCM kills the service. Main processing happens in a different thread running ServiceMain
            stopsignal = 0;
            Interlocked.MemoryBarrier();
            Thread serviceMainThread;

            serviceMainThread = new Thread(this.ServiceMain);
            serviceMainThread.Start();
        }
Пример #29
0
 void IActivityMonitorImpl.SetClientMinimalFilterDirty()
 {
     _actualFilterIsDirty = true;
     Interlocked.MemoryBarrier();
     // By signaling here the change to the bridge, we handle the case where the current
     // active thread works on a bridged monitor: the bridged monitor's _actualFilterIsDirty
     // is set to true and any interaction with its ActualFilter will trigger a resynchronization
     // of this _actualFilter.
     _output.BridgeTarget.TargetActualFilterChanged();
 }
Пример #30
0
        internal void StreamOperationCompletedCallback(IAsyncInfo completedOperation, AsyncStatus unusedCompletionStatus)
        {
            try
            {
                if (_callbackInvoked)
                {
                    throw new InvalidOperationException(SR.InvalidOperation_MultipleIOCompletionCallbackInvocation);
                }

                _callbackInvoked = true;

                // This happens in rare stress cases in Console mode and the WinRT folks said they are unlikely to fix this in Dev11.
                // Moreover, this can happen if the underlying WinRT stream has a faulty user implementation.
                // If we did not do this check, we would either get the same exception without the explaining message when dereferencing
                // completedOperation later, or we will get an InvalidOperation when processing the Op. With the check, they will be
                // aggregated and the user will know what went wrong.
                if (completedOperation == null)
                {
                    throw new NullReferenceException(SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo);
                }

                _completedOperation = completedOperation;

                // processCompletedOperationInCallback == false indicates that the stream is doing a blocking wait on the waitHandle of this IAsyncResult.
                // In that case calls on completedOperation may deadlock if completedOperation is not free threaded.
                // By setting processCompletedOperationInCallback to false the stream that created this IAsyncResult indicated that it
                // will call ProcessCompletedOperation after the waitHandle is signalled to fetch the results.

                if (_processCompletedOperationInCallback)
                {
                    ProcessCompletedOperation();
                }
            }
            catch (Exception ex)
            {
                _bytesCompleted = 0;
                _errorInfo      = ExceptionDispatchInfo.Capture(ex);
            }
            finally
            {
                _completed = true;
                Interlocked.MemoryBarrier();
                // From this point on, AsyncWaitHandle would create a handle that is readily set,
                // so we do not need to check if it is being produced asynchronously.
                if (_waitHandle != null)
                {
                    _waitHandle.Set();
                }
            }

            if (_userCompletionCallback != null)
            {
                _userCompletionCallback(this);
            }
        }