public void SetTimes(int newVal) => Interlocked.Exchange(ref this._remaining, newVal);
/// <summary> /// Cancels the current task. /// </summary> public void Cancel() { CancelAndDispose(Interlocked.Exchange(ref this.tokenSource, null)); }
public void Dispose() { Interlocked.Exchange(ref block, () => { })(); }
public void ResetEventsSent() { Interlocked.Exchange(ref eventsSent, 0L); }
internal void Reset(Int64 value = 0) { Interlocked.Exchange(ref _value, value); }
private static unsafe int AllocEntry(NativeHashMapData *data, int threadIndex) { int idx; int *nextPtrs = (int *)data->next; do { idx = data->firstFreeTLS[threadIndex * NativeHashMapData.IntsPerCacheLine]; if (idx < 0) { // Try to refill local cache Interlocked.Exchange(ref data->firstFreeTLS[threadIndex * NativeHashMapData.IntsPerCacheLine], -2); // If it failed try to get one from the never-allocated array if (data->allocatedIndexLength < data->capacity) { idx = Interlocked.Add(ref data->allocatedIndexLength, 16) - 16; if (idx < data->capacity - 1) { int count = Math.Min(16, data->capacity - idx); for (int i = 1; i < count; ++i) { nextPtrs[idx + i] = idx + i + 1; } nextPtrs[idx + count - 1] = -1; nextPtrs[idx] = -1; Interlocked.Exchange( ref data->firstFreeTLS[threadIndex * NativeHashMapData.IntsPerCacheLine], idx + 1); return(idx); } if (idx == data->capacity - 1) { Interlocked.Exchange( ref data->firstFreeTLS[threadIndex * NativeHashMapData.IntsPerCacheLine], -1); return(idx); } } Interlocked.Exchange(ref data->firstFreeTLS[threadIndex * NativeHashMapData.IntsPerCacheLine], -1); // Failed to get any, try to get one from another free list bool again = true; while (again) { again = false; for (int other = (threadIndex + 1) % JobsUtility.MaxJobThreadCount; other != threadIndex; other = (other + 1) % JobsUtility.MaxJobThreadCount) { do { idx = data->firstFreeTLS[other * NativeHashMapData.IntsPerCacheLine]; if (idx < 0) { break; } } while (Interlocked.CompareExchange( ref data->firstFreeTLS[other * NativeHashMapData.IntsPerCacheLine], nextPtrs[idx], idx) != idx); if (idx == -2) { again = true; } else if (idx >= 0) { nextPtrs[idx] = -1; return(idx); } } } throw new InvalidOperationException("HashMap is full"); } if (idx >= data->capacity) { throw new InvalidOperationException(string.Format("nextPtr idx {0} beyond capacity {1}", idx, data->capacity)); } } while (Interlocked.CompareExchange( ref data->firstFreeTLS[threadIndex * NativeHashMapData.IntsPerCacheLine], nextPtrs[idx], idx) != idx); nextPtrs[idx] = -1; return(idx); }
public void ResetBytesSent() { Interlocked.Exchange(ref bytesSent, 0L); }
/// <summary> /// Removes all the elements. /// </summary> public IEnumerable <T> ClearEnumerable() { return(Interlocked.Exchange(ref _mapper, _mapper = new Mapper <T>())); }
/// <summary> /// Returns the current value of the instance and sets it to <paramref name="newValue"/> as an atomic operation. /// </summary> /// <returns>The current value of the instance.</returns> public int GetAndSet(int newValue) { return Interlocked.Exchange(ref this.value, newValue); }
private void EnumerateNetworkMap() { NetworkManager.TraceDebug("EnumerateNetworkMap: attempting to reload", new object[0]); using (IAmCluster amCluster = ClusterFactory.Instance.Open()) { PersistentDagNetworkConfig persistentDagNetworkConfig = null; string text = null; Exception ex = null; using (DagConfigurationStore dagConfigurationStore = new DagConfigurationStore()) { dagConfigurationStore.Open(); persistentDagNetworkConfig = dagConfigurationStore.LoadNetworkConfig(out text); PersistentDagNetworkConfig persistentDagNetworkConfig2; if (persistentDagNetworkConfig == null) { persistentDagNetworkConfig2 = new PersistentDagNetworkConfig(); } else { persistentDagNetworkConfig2 = persistentDagNetworkConfig.Copy(); } IADDatabaseAvailabilityGroup localDag = Dependencies.ADConfig.GetLocalDag(); if (localDag == null) { NetworkManager.TraceError("EnumerateNetworkMap can't get the DAG!", new object[0]); } else { if (persistentDagNetworkConfig2.NetworkCompression != localDag.NetworkCompression) { persistentDagNetworkConfig2.NetworkCompression = localDag.NetworkCompression; } if (persistentDagNetworkConfig2.NetworkEncryption != localDag.NetworkEncryption) { persistentDagNetworkConfig2.NetworkEncryption = localDag.NetworkEncryption; } if (persistentDagNetworkConfig2.ManualDagNetworkConfiguration != localDag.ManualDagNetworkConfiguration) { persistentDagNetworkConfig2.ManualDagNetworkConfiguration = localDag.ManualDagNetworkConfiguration; } } this.NetworkCompression = persistentDagNetworkConfig2.NetworkCompression; this.NetworkEncryption = persistentDagNetworkConfig2.NetworkEncryption; this.ReplicationPort = persistentDagNetworkConfig2.ReplicationPort; this.ManualDagNetworkConfiguration = persistentDagNetworkConfig2.ManualDagNetworkConfiguration; if (this.m_portInLocalRegistry != this.ReplicationPort && TcpPortFallback.StorePortNumber(this.ReplicationPort)) { this.m_portInLocalRegistry = this.ReplicationPort; } NetworkDiscovery networkDiscovery = new NetworkDiscovery(); networkDiscovery.LoadClusterObjects(amCluster); if (this.ManualDagNetworkConfiguration) { networkDiscovery.LoadExistingConfiguration(persistentDagNetworkConfig2); } networkDiscovery.DetermineDnsStatus(); networkDiscovery.AggregateNetworks(true); if (!this.ManualDagNetworkConfiguration) { networkDiscovery.RemoveEmptyNets(); } ExchangeNetworkMap exchangeNetworkMap = new ExchangeNetworkMap(this); exchangeNetworkMap.Load(networkDiscovery); AmConfig config = AmSystemManager.Instance.Config; if (config.IsPAM) { try { exchangeNetworkMap.SynchronizeClusterNetworkRoles(amCluster); } catch (ClusCommonFailException ex2) { NetworkManager.TraceError("SynchronizeClusterNetworkRoles threw: {0}", new object[] { ex2 }); ex = ex2; } } exchangeNetworkMap.SetupPerfmon(); persistentDagNetworkConfig2 = exchangeNetworkMap.BuildPersistentDagNetworkConfig(); string text2 = persistentDagNetworkConfig2.Serialize(); bool flag = false; if (config.IsPAM) { if (persistentDagNetworkConfig == null || text != text2) { flag = true; Interlocked.Exchange(ref this.m_skipNextClusterRegistryEvent, 1); dagConfigurationStore.StoreNetworkConfig(text2); if (persistentDagNetworkConfig != null) { ReplayEventLogConstants.Tuple_DagNetworkConfigOld.LogEvent("DAGNET", new object[] { text }); } } } else if (this.m_lastWrittenClusterNetConfigXML != null && this.m_lastWrittenClusterNetConfigXML != text2) { flag = true; } if (flag) { ReplayEventLogConstants.Tuple_DagNetworkConfigNew.LogEvent("DAGNET", new object[] { text2 }); } this.m_lastWrittenClusterNetConfigXML = text2; DagNetConfig dagNetConfig = this.Convert2DagNetConfig(networkDiscovery); string text3 = dagNetConfig.Serialize(); if (this.m_lastWrittenEseReplNetConfigXML == null || this.EseReplDagNetConfigIsStale || text3 != this.m_lastWrittenEseReplNetConfigXML) { DagNetEnvironment.PublishDagNetConfig(text3); this.EseReplDagNetConfigIsStale = false; } this.m_lastWrittenEseReplNetConfigXML = text3; this.m_mapLoadTime = ExDateTime.Now; this.m_netMap = exchangeNetworkMap; NetworkManager.TraceDebug("EnumerateNetworkMap: completed reload", new object[0]); AmSystemManager instance = AmSystemManager.Instance; if (instance != null) { AmNetworkMonitor networkMonitor = instance.NetworkMonitor; if (networkMonitor != null) { networkMonitor.RefreshMapiNetwork(); } } if (ex != null) { throw ex; } } } }
public bool TrySetInvoked() { return(Interlocked.Exchange(ref _callbackInvoked, 1) == 0); }
public void Exit() { var state = Interlocked.Exchange(ref _isInCriticalSection, 0); Debug.Assert(state == 1, "Expected to be in a critical section"); }
public Task FlushAsync() { Interlocked.Exchange(ref _flush, () => { }).Invoke(); return(TaskAsyncHelper.Empty); }
/// <summary> /// Routes a stream to an appropriate stream-type-specific processor /// </summary> private async Task ProcessServerStreamAsync(QuicStream stream) { ArrayBuffer buffer = default; try { await using (stream.ConfigureAwait(false)) { if (stream.CanWrite) { // Server initiated bidirectional streams are either push streams or extensions, and we support neither. throw new Http3ConnectionException(Http3ErrorCode.StreamCreationError); } buffer = new ArrayBuffer(initialSize: 32, usePool: true); int bytesRead; try { bytesRead = await stream.ReadAsync(buffer.AvailableMemory, CancellationToken.None).ConfigureAwait(false); } catch (QuicStreamAbortedException) { // Treat identical to receiving 0. See below comment. bytesRead = 0; } if (bytesRead == 0) { // https://quicwg.org/base-drafts/draft-ietf-quic-http.html#name-unidirectional-streams // A sender can close or reset a unidirectional stream unless otherwise specified. A receiver MUST // tolerate unidirectional streams being closed or reset prior to the reception of the unidirectional // stream header. return; } buffer.Commit(bytesRead); // Stream type is a variable-length integer, but we only check the first byte. There is no known type requiring more than 1 byte. switch (buffer.ActiveSpan[0]) { case (byte)Http3StreamType.Control: if (Interlocked.Exchange(ref _haveServerControlStream, 1) != 0) { // A second control stream has been received. throw new Http3ConnectionException(Http3ErrorCode.StreamCreationError); } // Discard the stream type header. buffer.Discard(1); // Ownership of buffer is transferred to ProcessServerControlStreamAsync. ArrayBuffer bufferCopy = buffer; buffer = default; await ProcessServerControlStreamAsync(stream, bufferCopy).ConfigureAwait(false); return; case (byte)Http3StreamType.QPackDecoder: if (Interlocked.Exchange(ref _haveServerQpackDecodeStream, 1) != 0) { // A second QPack decode stream has been received. throw new Http3ConnectionException(Http3ErrorCode.StreamCreationError); } // The stream must not be closed, but we aren't using QPACK right now -- ignore. buffer.Dispose(); await stream.CopyToAsync(Stream.Null).ConfigureAwait(false); return; case (byte)Http3StreamType.QPackEncoder: if (Interlocked.Exchange(ref _haveServerQpackEncodeStream, 1) != 0) { // A second QPack encode stream has been received. throw new Http3ConnectionException(Http3ErrorCode.StreamCreationError); } // We haven't enabled QPack in our SETTINGS frame, so we shouldn't receive any meaningful data here. // However, the standard says the stream must not be closed for the lifetime of the connection. Just ignore any data. buffer.Dispose(); await stream.CopyToAsync(Stream.Null).ConfigureAwait(false); return; case (byte)Http3StreamType.Push: // We don't support push streams. // Because no maximum push stream ID was negotiated via a MAX_PUSH_ID frame, server should not have sent this. Abort the connection with H3_ID_ERROR. throw new Http3ConnectionException(Http3ErrorCode.IdError); default: // Unknown stream type. Per spec, these must be ignored and aborted but not be considered a connection-level error. if (NetEventSource.Log.IsEnabled()) { // Read the rest of the integer, which might be more than 1 byte, so we can log it. long unknownStreamType; while (!VariableLengthIntegerHelper.TryRead(buffer.ActiveSpan, out unknownStreamType, out _)) { buffer.EnsureAvailableSpace(VariableLengthIntegerHelper.MaximumEncodedLength); bytesRead = await stream.ReadAsync(buffer.AvailableMemory, CancellationToken.None).ConfigureAwait(false); if (bytesRead == 0) { unknownStreamType = -1; break; } buffer.Commit(bytesRead); } NetEventSource.Info(this, $"Ignoring server-initiated stream of unknown type {unknownStreamType}."); } stream.AbortWrite((long)Http3ErrorCode.StreamCreationError); return; } } } catch (Exception ex) { Abort(ex); } finally { buffer.Dispose(); } }
public bool CheckModule() { if (!CheckModule(true, EModuleType.Module)) { return(false); } Interlocked.Exchange(ref _LastCheck, 0); try { if (((Module)_Current).IsCheckIntrusive()) { _IO.WriteInfo(Lang.Get("Can_Be_Intrusive")); string line = _IO.ReadLine(null, null); if (!(bool)ConvertHelper.ConvertTo(line, typeof(bool))) { return(false); } } Module m = (Module)_Current.Clone(); m.Prepare(_Current); Thread th = _IO.CancelableThread = new Thread(new ParameterizedThreadStart(checkModule)); th.Name = "CHECK " + _Current.FullPath; th.IsBackground = true; th.Start(m); th.Join(); //if (th.ThreadState == System.Threading.ThreadState.Aborted) //{ // // Check abort // _IO.WriteError(Lang.Get("Aborting")); //} return((ECheck)_LastCheck == ECheck.Ok); } catch (Exception e) { _Current.WriteError(e.Message); } finally { if (_IO.CancelableThread != null) { _IO.CancelableThread = null; switch ((ECheck)_LastCheck) { case ECheck.CantCheck: _Current.WriteInfo(Lang.Get("Check_CantCheck")); break; case ECheck.Error: _Current.WriteInfo(Lang.Get("Check_Result"), Lang.Get("Error"), ConsoleColor.Red); break; case ECheck.NotSure: _Current.WriteInfo(Lang.Get("Check_NotSure")); break; case ECheck.Ok: _Current.WriteInfo(Lang.Get("Check_Result"), Lang.Get("Ok"), ConsoleColor.Green); break; } } } return(false); }
/// <summary> /// 循环处理命令 /// </summary> /// <param name="isCommand"></param> /// <returns></returns> private bool loop(bool isCommand) { START: int receiveSize = receiveCount - receiveIndex; if (receiveSize == 0) { receiveCount = receiveIndex = 0; if (isCommand) return false; } else { if (receiveSize >= sizeof(int)) { byte* start = receiveDataStart + receiveIndex; if ((command = *(int*)start) < 0) { if (receiveSize >= sizeof(int) * 2) { if ((dataSize = *(int*)(start + sizeof(int))) <= (compressionDataSize = -command) || compressionDataSize == 0) return false; receiveIndex += sizeof(int) * 2; receiveSize -= sizeof(int) * 2; if (compressionDataSize <= receiveSize) { if (doCompressionCommand()) { isCommand = false; goto START; } return false; } return receiveCompressionCommandData(); } if (isCommand) return false; goto COPY; } else { CommandIndex = (uint)command & TcpServer.Server.CommandFlagsAnd; if (Server.IsCommand(command &= (int)TcpServer.Server.CommandIndexAnd) && IsCommand(command)) { if (command != TcpServer.Server.CheckCommandIndex) { if ((CommandIndex & (uint)TcpServer.CommandFlags.NullData) == 0) { if (receiveSize >= sizeof(int) * 2) { if ((compressionDataSize = *(int*)(start + sizeof(int))) > 0) { if (compressionDataSize <= receiveCount - (receiveIndex += sizeof(int) * 2)) { doCommandLoop(); isCommand = false; goto START; } bool isDoCommand = false; if (receiveCommandData(ref isDoCommand)) { if (isDoCommand) { isCommand = false; goto START; } return true; } } return false; } if (isCommand) return false; goto COPY; } if (command != TcpServer.Server.RemoteExpressionCommandIndex && command != TcpServer.Server.RemoteExpressionNodeIdCommandIndex) Server.DoCommand(command, Sender, ref SubArray<byte>.Null); else return false; } receiveIndex += sizeof(int); isCommand = false; goto START; } } return false; } else if (isCommand) return false; COPY: Memory.SimpleCopyNotNull64(receiveDataStart + receiveIndex, receiveDataStart, receiveCount = receiveSize); receiveIndex = 0; } Socket socket = Socket; if (socket != null) { ReceiveType = TcpServer.ServerSocketReceiveType.Command; #if DOTNET2 socket.BeginReceive(ReceiveBuffer.Buffer, ReceiveBuffer.StartIndex + receiveCount, receiveBufferSize - receiveCount, SocketFlags.None, out socketError, onReceiveAsyncCallback, socket); if (socketError == SocketError.Success) return true; #else #if !DotNetStandard while (Interlocked.CompareExchange(ref receiveAsyncLock, 1, 0) != 0) Thread.Sleep(0); #endif receiveAsyncEventArgs.SetBuffer(ReceiveBuffer.StartIndex + receiveCount, receiveBufferSize - receiveCount); if (socket.ReceiveAsync(receiveAsyncEventArgs)) { #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 0); #endif return true; } if (receiveAsyncEventArgs.SocketError == SocketError.Success) { #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 0); #endif receiveCount += receiveAsyncEventArgs.BytesTransferred; isCommand = true; goto START; } socketError = receiveAsyncEventArgs.SocketError; #endif } return false; }
private void EndCollectionThread() { Interlocked.Exchange(ref this.collectionThread, null)?.Stop(wait: false); }
///// <summary> ///// 命令处理委托 ///// </summary> ///// <param name="buffer"></param> //[MethodImpl(AutoCSer.MethodImpl.AggressiveInlining)] //private void doCommand(ref SubBuffer.PoolBufferFull buffer) //{ // SubArray<byte> data = new SubArray<byte> { Array = buffer.Buffer, Start = buffer.StartIndex, Length = compressionDataSize }; // Server.DoCommand(command, Sender, ref data); // buffer.PoolBuffer.Free(); //} /// <summary> /// 检查命令数据 /// </summary> /// <returns></returns> private bool receiveCompressionCommandData() { int nextSize = compressionDataSize - (receiveCount - receiveIndex); if (compressionDataSize <= receiveBufferSize) { if (receiveIndex + compressionDataSize > receiveBufferSize) { Memory.CopyNotNull(receiveDataStart + receiveIndex, receiveDataStart, receiveCount -= receiveIndex); receiveIndex = 0; } ReceiveType = TcpServer.ServerSocketReceiveType.CompressionData; #if !DOTNET2 RECEIVE: #endif Socket socket = Socket; if (socket != null) { #if DOTNET2 socket.BeginReceive(ReceiveBuffer.Buffer, ReceiveBuffer.StartIndex + receiveCount, nextSize, SocketFlags.None, out socketError, onReceiveAsyncCallback, socket); if (socketError == SocketError.Success) return true; #else #if !DotNetStandard while (Interlocked.CompareExchange(ref receiveAsyncLock, 1, 0) != 0) Thread.Sleep(0); #endif receiveAsyncEventArgs.SetBuffer(ReceiveBuffer.StartIndex + receiveCount, nextSize); if (socket.ReceiveAsync(receiveAsyncEventArgs)) { #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 0); #endif return true; } if (receiveAsyncEventArgs.SocketError == SocketError.Success) { int count = receiveAsyncEventArgs.BytesTransferred; #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 0); #endif receiveCount += count; if ((nextSize -= count) == 0) return doCompressionCommand() && isReceiveCommand(); goto RECEIVE; } socketError = receiveAsyncEventArgs.SocketError; #endif } } else { SubBuffer.Pool.GetBuffer(ref ReceiveBigBuffer, compressionDataSize); if (ReceiveBigBuffer.PoolBuffer.Pool == null) ++Server.ReceiveNewBufferCount; receiveBigBufferCount = receiveCount - receiveIndex; ReceiveType = TcpServer.ServerSocketReceiveType.CompressionBigData; #if !DOTNET2 BIGRECEIVE: #endif Socket socket = Socket; if (socket != null) { #if DOTNET2 socket.BeginReceive(ReceiveBigBuffer.Buffer, ReceiveBigBuffer.StartIndex + receiveBigBufferCount, nextSize, SocketFlags.None, out socketError, onReceiveAsyncCallback, socket); if (socketError == SocketError.Success) return true; #else #if !DotNetStandard while (Interlocked.CompareExchange(ref receiveAsyncLock, 1, 0) != 0) Thread.Sleep(0); #endif receiveAsyncEventArgs.SetBuffer(ReceiveBigBuffer.Buffer, ReceiveBigBuffer.StartIndex + receiveBigBufferCount, nextSize); if (socket.ReceiveAsync(receiveAsyncEventArgs)) { #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 0); #endif return true; } if (receiveAsyncEventArgs.SocketError == SocketError.Success) { int count = receiveAsyncEventArgs.BytesTransferred; #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 0); #endif receiveBigBufferCount += count; if ((nextSize -= count) == 0) return doCompressionBigDataCommand() && isReceiveCommand(); goto BIGRECEIVE; } socketError = receiveAsyncEventArgs.SocketError; #endif } } return false; }
public void ResetBytesReceived() { Interlocked.Exchange(ref bytesReceived, 0L); }
/// <summary> /// 获取数据 /// </summary> private void compressionDataAsync() { try { #if DOTNET2 Socket socket = new Net.UnionType { Value = receiveAsyncEventArgs.AsyncState }.Socket; if (socket == Socket) { receiveCount += socket.EndReceive(receiveAsyncEventArgs, out socketError); if (socketError == SocketError.Success) { #else CHECK: if (receiveAsyncEventArgs.SocketError == SocketError.Success) { receiveCount += receiveAsyncEventArgs.BytesTransferred; #endif int nextSize = compressionDataSize - (receiveCount - receiveIndex); if (nextSize == 0) { if (doCompressionCommand() && isReceiveCommand()) return; } else { #if DOTNET2 if (socket == Socket) { socket.BeginReceive(ReceiveBuffer.Buffer, ReceiveBuffer.StartIndex + receiveCount, nextSize, SocketFlags.None, out socketError, onReceiveAsyncCallback, socket); if (socketError == SocketError.Success) return; } #else Socket socket = Socket; if (socket != null) { #if !DotNetStandard while (Interlocked.CompareExchange(ref receiveAsyncLock, 1, 0) != 0) Thread.Sleep(0); #endif receiveAsyncEventArgs.SetBuffer(ReceiveBuffer.StartIndex + receiveCount, nextSize); if (socket.ReceiveAsync(receiveAsyncEventArgs)) { #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 0); #endif return; } #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 0); #endif goto CHECK; } #endif } #if DOTNET2 } #endif } #if !DOTNET2 else socketError = receiveAsyncEventArgs.SocketError; #endif } catch (Exception error) { Server.Log.Add(AutoCSer.Log.LogType.Debug, error); } close(); }
public void ResetEventsReceived() { Interlocked.Exchange(ref eventsReceived, 0L); }
public static void RunWithProcessorPressure(int threadCount, int lockCount, double activePercent, double lockChancePercent, Action a) { var stopped = 0; var started = new CountdownEvent(threadCount); var ts = new Thread[threadCount]; var locks = Enumerable.Range(0, lockCount).Select(_ => new object()).ToArray(); for (int i = 0; i < threadCount; i++) { var id = i; var t = ts[i] = new Thread(() => { var rand = new Random(); started.Signal(); var sw = Stopwatch.StartNew(); var run = TimeSpan.Zero; while (Thread.VolatileRead(ref stopped) == 0) { var busy = new Stopwatch(); while (Thread.VolatileRead(ref stopped) == 0 && (double)run.Ticks / (double)sw.ElapsedTicks < activePercent) { busy.Restart(); const int RUN = 0; const int BLOCK = 1; var action = lockCount > 0 && rand.Next() % 100 <= lockChancePercent * 100 ? BLOCK : RUN; switch (action) { case RUN: //Console.WriteLine("~" + id); while (busy.ElapsedMilliseconds < 10) { ; } break; case BLOCK: //Console.WriteLine("!" + id); lock (locks[rand.Next(0, lockCount)]) Thread.Sleep(rand.Next(100, 1000)); break; } run += busy.Elapsed; } Thread.Sleep(rand.Next(100, 1000)); } }); t.Start(); } started.Wait(); try { a(); } finally { Interlocked.Exchange(ref stopped, 1); foreach (var t in ts) { t.Join(); } } }
public virtual void Reset() { Interlocked.Exchange(ref counter, 0); }
public static void RunWithMemoryPressure(int minBytes, int maxBytes, double activePercent, Action a) { var started = new ManualResetEvent(false); var stopped = 0; var avg = (minBytes + maxBytes) / 2; var MIN = avg / 1000; var MAX = avg / 10; var allocator = new Thread(() => { var rand = new Random(); var roots = new List <byte[]>(); var bytes = 0; while (bytes < avg) { var n = rand.Next(MIN, MAX); bytes += n; roots.Add(new byte[n]); } started.Set(); long avgSum = 0; long count = 0; const int DEC = 0; const int INC = 1; var trendPhase = 0; var trendLength = 0; while (Thread.VolatileRead(ref stopped) == 0) { if (trendLength-- == 0) { trendPhase = rand.Next(0, 1000) % 2; trendLength = rand.Next(1, 10); } var mem = TimeSpan.Zero; var sw = Stopwatch.StartNew(); var busy = new Stopwatch(); while (Thread.VolatileRead(ref stopped) == 0 && (double)mem.Ticks / (double)sw.ElapsedTicks < activePercent) { busy.Restart(); var runFor = rand.Next(10, 100); while (busy.ElapsedMilliseconds < runFor) { if (trendPhase == INC) { if (bytes < maxBytes) { var n = rand.Next(MIN, MAX); bytes += n; roots.Add(new byte[n]); continue; } else { trendPhase = DEC; } } if (trendPhase == DEC) { if (bytes > minBytes) { if (roots.Count > 0) { var i = rand.Next(0, roots.Count); bytes -= roots[i].Length; roots.RemoveAt(i); } continue; } else { trendPhase = INC; } } } mem += busy.Elapsed; } var sleepFor = rand.Next(100, 1000); Thread.Sleep(sleepFor); avgSum += bytes; count++; //Console.WriteLine(bytes + " - Avg = " + avgSum / count); } }); allocator.Start(); started.WaitOne(); try { a(); } finally { Interlocked.Exchange(ref stopped, 1); allocator.Join(); } }
/// <summary> /// Start polling the node-dss server with a GET request, and continue to do so /// until <see cref="StopPollingAsync"/> is called. /// </summary> /// <returns>Returns <c>true</c> if polling effectively started with this call.</returns> /// <remarks> /// The <see cref="LocalPeerId"/> field must be set before calling this method. /// This method can safely be called multiple times, and will do nothing if /// polling is already underway or waiting to be stopped. /// </remarks> public bool StartPollingAsync(CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(LocalPeerId)) { throw new InvalidOperationException("Cannot start polling with empty LocalId."); } lock (_pollingLock) { if (_isPolling) { return(false); } _isPolling = true; _cancellationTokenSource = new CancellationTokenSource(); } RaisePropertyChanged("IsPolling"); // Build the GET polling request string requestUri = $"{_httpServerAddress}data/{LocalPeerId}"; long lastPollTimeTicks = DateTime.UtcNow.Ticks; long pollTimeTicks = TimeSpan.FromMilliseconds(PollTimeMs).Ticks; var masterTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, cancellationToken); var masterToken = masterTokenSource.Token; masterToken.Register(() => { lock (_pollingLock) { _isPolling = false; _cancellationTokenSource.Dispose(); _cancellationTokenSource = null; } RaisePropertyChanged("IsPolling"); Interlocked.Exchange(ref _connectedEventFired, 0); OnDisconnect?.Invoke(); OnPollingDone?.Invoke(); masterTokenSource.Dispose(); }); // Prepare the repeating poll task. // In order to poll at the specified frequency but also avoid overlapping requests, // use a repeating task which re-schedule itself on completion, either immediately // if the polling delay is elapsed, or at a later time otherwise. async void PollServer() { try { // Polling loop while (true) { masterToken.ThrowIfCancellationRequested(); // Send GET request to DSS server. lastPollTimeTicks = DateTime.UtcNow.Ticks; HttpResponseMessage response = await _httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, masterToken); // On first successful HTTP request, raise the connected event if (0 == Interlocked.Exchange(ref _connectedEventFired, 1)) { OnConnect?.Invoke(); } masterToken.ThrowIfCancellationRequested(); // In order to avoid exceptions in GetStreamAsync() when the server returns a non-success status code (e.g. 404), // first get the HTTP headers, check the status code, then if successful wait for content. if (response.IsSuccessStatusCode) { string jsonMsg = await response.Content.ReadAsStringAsync(); masterToken.ThrowIfCancellationRequested(); var jsonSettings = new JsonSerializerSettings { Error = (object s, ErrorEventArgs e) => throw new Exception("JSON error: " + e.ErrorContext.Error.Message) }; Message msg = JsonConvert.DeserializeObject <Message>(jsonMsg, jsonSettings); if (msg != null) { OnMessage?.Invoke(msg); } else { throw new Exception("Failed to deserialize signaler message from JSON."); } } masterToken.ThrowIfCancellationRequested(); // Delay next loop iteration if current polling was faster than target poll duration long curTime = DateTime.UtcNow.Ticks; long deltaTicks = curTime - lastPollTimeTicks; long remainTicks = pollTimeTicks - deltaTicks; if (remainTicks > 0) { int waitTimeMs = new TimeSpan(remainTicks).Milliseconds; await Task.Delay(waitTimeMs); } } } catch (OperationCanceledException) { // Manual cancellation via UI, do not report error } catch (Exception ex) { OnFailure?.Invoke(ex); } } // Start the poll task immediately Task.Run(PollServer, masterToken); return(true); }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() => Interlocked.Exchange(ref _pathGeometry, null)?.Dispose();
public void Dispose() { Interlocked.Exchange(ref inner, ActionDisposable.Empty).Dispose(); }
private void ExitReconnecting() { Interlocked.Exchange(ref _reconnecting, 0); }
internal void OnHeartbeat(bool ifConnectedOnly) { bool runThisTime = false; try { runThisTime = !isDisposed && Interlocked.CompareExchange(ref beating, 1, 0) == 0; if (!runThisTime) { return; } uint index = (uint)Interlocked.Increment(ref profileLogIndex); long newSampleCount = Interlocked.Read(ref operationCount); Interlocked.Exchange(ref profileLog[index % ProfileLogSamples], newSampleCount); Interlocked.Exchange(ref profileLastLog, newSampleCount); Trace("OnHeartbeat: " + (State)state); switch (state) { case (int)State.Connecting: int connectTimeMilliseconds = unchecked (Environment.TickCount - VolatileWrapper.Read(ref connectStartTicks)); if (connectTimeMilliseconds >= Multiplexer.RawConfig.ConnectTimeout) { LastException = ExceptionFactory.UnableToConnect("ConnectTimeout"); Trace("Aborting connect"); // abort and reconnect var snapshot = physical; bool isCurrent; State oldState; OnDisconnected(ConnectionFailureType.UnableToConnect, snapshot, out isCurrent, out oldState); using (snapshot) { } // dispose etc TryConnect(null); } if (!ifConnectedOnly) { AbortUnsent(); } break; case (int)State.ConnectedEstablishing: case (int)State.ConnectedEstablished: var tmp = physical; if (tmp != null) { if (state == (int)State.ConnectedEstablished) { tmp.Bridge.ServerEndPoint.ClearUnselectable(UnselectableFlags.DidNotRespond); } tmp.OnHeartbeat(); int writeEverySeconds = ServerEndPoint.WriteEverySeconds, checkConfigSeconds = Multiplexer.RawConfig.ConfigCheckSeconds; if (state == (int)State.ConnectedEstablished && ConnectionType == ConnectionType.Interactive && checkConfigSeconds > 0 && ServerEndPoint.LastInfoReplicationCheckSecondsAgo >= checkConfigSeconds && ServerEndPoint.CheckInfoReplication()) { // that serves as a keep-alive, if it is accepted } else if (writeEverySeconds > 0 && tmp.LastWriteSecondsAgo >= writeEverySeconds) { Trace("OnHeartbeat - overdue"); if (state == (int)State.ConnectedEstablished) { KeepAlive(); } else { bool ignore; State oldState; OnDisconnected(ConnectionFailureType.SocketFailure, tmp, out ignore, out oldState); } } else if (!queue.Any() && tmp.GetSentAwaitingResponseCount() != 0) { // there's a chance this is a dead socket; sending data will shake that // up a bit, so if we have an empty unsent queue and a non-empty sent // queue, test the socket KeepAlive(); } } break; case (int)State.Disconnected: if (!ifConnectedOnly) { AbortUnsent(); Multiplexer.Trace("Resurrecting " + this.ToString()); GetConnection(null); } break; default: if (!ifConnectedOnly) { AbortUnsent(); } break; } } catch (Exception ex) { OnInternalError(ex); Trace("OnHeartbeat error: " + ex.Message); } finally { if (runThisTime) { Interlocked.Exchange(ref beating, 0); } } }
public static char[] GetReadBuffer() => Interlocked.Exchange(ref __readBuffer, null)?.Target as char[] ?? new char[BUF_LENGTH];