当前位置: 首页>>代码示例>>C#>>正文


C# ConcurrentDictionary.Clear方法代码示例

本文整理汇总了C#中ConcurrentDictionary.Clear方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentDictionary.Clear方法的具体用法?C# ConcurrentDictionary.Clear怎么用?C# ConcurrentDictionary.Clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ConcurrentDictionary的用法示例。


在下文中一共展示了ConcurrentDictionary.Clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetColorCount

        /// <summary>
        /// Returns the color count from the palette of the given image.
        /// </summary>
        /// <param name="image">
        /// The <see cref="System.Drawing.Image"/> to get the colors from.
        /// </param>
        /// <returns>
        /// The <see cref="int"/> representing the color count.
        /// </returns>
        public static int GetColorCount(Image image)
        {
            ConcurrentDictionary<Color, Color> colors = new ConcurrentDictionary<Color, Color>();
            int width = image.Width;
            int height = image.Height;

            using (FastBitmap fastBitmap = new FastBitmap(image))
            {
                Parallel.For(
                    0,
                    height,
                    y =>
                    {
                        for (int x = 0; x < width; x++)
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            Color color = fastBitmap.GetPixel(x, y);
                            colors.TryAdd(color, color);
                        }
                    });
            }

            int count = colors.Count;
            colors.Clear();
            return count;
        }
开发者ID:GertyEngrie,项目名称:ImageProcessor,代码行数:35,代码来源:FormatUtilities.cs

示例2: DebuggerDecompilerService

		static DebuggerDecompilerService()
		{
			DebugInformation = new ConcurrentDictionary<int, DecompileInformation>();
			ProjectService.SolutionClosed += delegate {
				DebugInformation.Clear();
				GC.Collect();
			};
		}
开发者ID:nylen,项目名称:SharpDevelop,代码行数:8,代码来源:DebuggerDecompilerService.cs

示例3: ObjectBaseValidator

 static ObjectBaseValidator()
 {
     Cache = new ConcurrentDictionary<Type, ObjectBaseValidator>();
     DxSettings.GlobalSettings.PropertyChanged += (sender, e) =>
     {
         if (e.PropertyName == "CacheTypeCheckers" && !DxSettings.GlobalSettings.CacheTypeCheckers)
             Cache.Clear();
     };
 }
开发者ID:ShaneGH,项目名称:Dynamox,代码行数:9,代码来源:ObjectBaseValidator.cs

示例4: CreateBlock

    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<Bucket> target,
      string rootNamespace, 
      bool removeZeroGauges,
      IIntervalService intervalService,
      ILog log)
    {
      var gauges = new ConcurrentDictionary<string, double>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";

      var incoming = new ActionBlock<StatsdMessage>(p =>
        {
          var gauge = p as Gauge;
          gauges.AddOrUpdate(gauge.Name, gauge.Value, (key, oldValue) => gauge.Value);
        },
        Utility.UnboundedExecution());

      intervalService.Elapsed += (sender, e) =>
        {
          if (gauges.Count == 0)
          {
            return;
          }
          var items = gauges.ToArray();
          var bucket = new GaugesBucket(items, e.Epoch, ns);
          if (removeZeroGauges)
          {
            // Get all zero-value gauges
            double placeholder;
            var zeroGauges = 0;
            for (int index = 0; index < items.Length; index++)
            {
              if (items[index].Value == 0)
              {
                gauges.TryRemove(items[index].Key, out placeholder);
                zeroGauges += 1;
              }
            }
            if (zeroGauges > 0)
            {
              log.InfoFormat("Removed {0} empty gauges.", zeroGauges);
            }
          }
          
          gauges.Clear();
          target.Post(bucket);
        };

      incoming.Completion.ContinueWith(p =>
        {
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
开发者ID:houcine,项目名称:statsd.net,代码行数:55,代码来源:TimedGaugeAggregatorBlockFactory.cs

示例5: PlatformFactory

 static PlatformFactory()
 {
     HelperCache = new ConcurrentDictionary<string, HelperBase>();
     //添加监听
     ConfigManager.Change += file =>
     {
         if (file == ConfigUtils<PlatformConfig>.Instance.FileName)
         {
             HelperCache.Clear();
         }
     };
 }
开发者ID:shoy160,项目名称:Shoy.Common,代码行数:12,代码来源:PlatformFactory.cs

示例6: CreateBlock

    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<Bucket> target,
      string rootNamespace, 
      IIntervalService intervalService,
      int percentile,
      string percentileName,
      ILog log,
      int maxItemsPerBucket = 1000)
    {
      var latencies = new ConcurrentDictionary<string, DatapointBox>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";
      var random = new Random();
      percentileName = "." + ( percentileName ?? ( "p" + percentile ) );

      var incoming = new ActionBlock<StatsdMessage>( p =>
        {
          var latency = p as Timing;
          latencies.AddOrUpdate(latency.Name,
              (key) =>
              {
                return new DatapointBox(maxItemsPerBucket, latency.ValueMS); 
              },
              (key, bag) =>
              {
                bag.Add(latency.ValueMS);
                return bag;
              });
        },
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

      intervalService.Elapsed += (sender, e) =>
        {
          if (latencies.Count == 0)
          {
            return;
          }
          var bucket = new PercentileBucket(latencies.ToArray(),
            e.Epoch,
            ns,
            percentileName,
            percentile);
          latencies.Clear();
          target.Post(bucket);
        };

      incoming.Completion.ContinueWith(p =>
        {
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
开发者ID:BookSwapSteve,项目名称:statsd.net,代码行数:52,代码来源:TimedLatencyPercentileAggregatorBlockFactory.cs

示例7: GuardAgainstRace

        public void GuardAgainstRace()
        {
            // This code will trigger the load of CDSCollectionETWBCLProvider
            var dictionary = new ConcurrentDictionary<int, int>();
            dictionary.Clear();

            var log = typeof(ConcurrentDictionary<int, int>)
                .Assembly
                .GetType("System.Collections.Concurrent.CDSCollectionETWBCLProvider")
                .GetField("Log", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
                .GetValue(null);
            Assert.NotNull(log);
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:13,代码来源:EventListenerGuard.cs

示例8: CreateBlock

    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<SetsBucket> target,
      string rootNamespace, 
      IIntervalService intervalService,
      ILog log)
    {
      var sets = new ConcurrentDictionary<string, ConcurrentDictionary<int, bool>>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";

      var incoming = new ActionBlock<StatsdMessage>(p =>
        {
          var set = p as Set;
          sets.AddOrUpdate(set.Name, 
            (key) =>
              {
                var setDict = new ConcurrentDictionary<int, bool>();
                setDict.AddOrUpdate( set.Value, ( key2 ) => true, ( key2, oldValue ) => true );
                return setDict;
              },
            (key, setDict) =>
              {
                setDict.AddOrUpdate( set.Value, ( key2 ) => true, ( key2, oldValue ) => true );
                return setDict;
              });
        },
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

      intervalService.Elapsed += (sender, e) =>
        {
          if (sets.Count == 0)
          {
            return;
          }
          var rawData = sets.ToArray();
          sets.Clear();
          var bucket = new SetsBucket(
            rawData.Select(p =>
              new KeyValuePair<string, List<KeyValuePair<int, bool>>>(p.Key, p.Value.ToList())
            ).ToList(),
            e.Epoch,
            ns);

          target.Post(bucket);
        };
      incoming.Completion.ContinueWith(p =>
        {
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
开发者ID:joshclark,项目名称:statsd.net,代码行数:51,代码来源:TimedSetAggregatorBlockFactory.cs

示例9: MultiClampDevice

        /// <summary>
        /// Constructs a new MultiClampDevice
        /// </summary>
        /// <param name="commander">MultiClampCommander instance</param>
        /// <param name="c">Symphony Controller instance</param>
        /// <param name="background">Dictionary of background Measurements for each MultiClamp operating mode</param>
        public MultiClampDevice(IMultiClampCommander commander, Controller c, IDictionary<MultiClampInterop.OperatingMode, IMeasurement> background)
            : base("Multiclamp-" + commander.SerialNumber + "-" + commander.Channel, "Molecular Devices", c)
        {
            InputParameters = new ConcurrentDictionary<DateTimeOffset, MultiClampParametersChangedArgs>();
            OutputParameters = new ConcurrentDictionary<DateTimeOffset, MultiClampParametersChangedArgs>();

            Commander = commander;
            Commander.ParametersChanged += (sender, mdArgs) =>
                {
                    lock (_bindLock)
                    {
                        log.DebugFormat(
                            "MultiClamp parameters changed. Mode = {0}, External Command Sensistivity Units = {1} Timestamp = {2}",
                            mdArgs.Data.OperatingMode,
                            mdArgs.Data.ExternalCommandSensitivityUnits,
                            mdArgs.TimeStamp);

                        if (!HasBoundInputStream)
                            InputParameters.Clear();

                        InputParameters[mdArgs.TimeStamp.ToUniversalTime()] = mdArgs;

                        if (!HasBoundOutputStream)
                            OutputParameters.Clear();

                        OutputParameters[mdArgs.TimeStamp.ToUniversalTime()] = mdArgs;

                        foreach (var outputStream in OutputStreams.Where(s => s.DAQ != null && s.DAQ.IsHardwareReady && !s.DAQ.IsRunning))
                        {
                            log.DebugFormat("Setting new background for stream {0}", outputStream.Name);
                            try
                            {
                                outputStream.ApplyBackground();
                            }
                            catch (Exception x)
                            {
                                log.ErrorFormat("Error applying new background: {0}", x);
                                throw;
                            }

                        }
                    }
                };
            Commander.RequestTelegraphValue();

            Backgrounds = background;
        }
开发者ID:Symphony-DAS,项目名称:symphony-core,代码行数:53,代码来源:MulticlampDevice.cs

示例10: Thread

        void IProxyService.Start()
        {
            ProxyClients = new ConcurrentDictionary<IntPtr, Socket>();
            new Thread(async t =>
            {
                ProxyConnection = new TcpListener(IPAddress.Any, 3939);
                ProxyConnection.Start();

                while (true)
                {
                    var socket = await ProxyConnection.AcceptSocketAsync();
                    ProxyClients.Clear();
                    ProxyClients.TryAdd(socket.Handle, socket);

                    var socketAsyncEventArgs = new SocketAsyncEventArgs();
                    byte[] buffer = new byte[8192];
                    socketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
                    socketAsyncEventArgs.Completed += SocketAsyncEventArgs_Completed;
                    socket.ReceiveAsync(socketAsyncEventArgs);
                }
            }).Start();
        }
开发者ID:buddyfavors,项目名称:CoCSharp,代码行数:22,代码来源:JsonSocketProxyService.cs

示例11: CreateBlock

    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<Bucket> target,
      string rootNamespace, 
      IIntervalService intervalService,
      ILog log)
    {
      var counters = new ConcurrentDictionary<string, double>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : (rootNamespace + ".");

      var incoming = new ActionBlock<StatsdMessage>(p =>
        {
          var counter = p as Counter;
          counters.AddOrUpdate(counter.Name, counter.Value, (key, oldValue) => oldValue + counter.Value);
        },
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

      intervalService.Elapsed += (sender, e) =>
        {
          if (counters.Count == 0)
          {
            return;
          }

          var bucket = new CounterBucket(counters.ToArray(), e.Epoch, ns);
          counters.Clear();
          target.Post(bucket);
        };

      incoming.Completion.ContinueWith(p =>
        {
          log.Info("TimedCounterAggregatorBlock completing.");
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
开发者ID:houcine,项目名称:statsd.net,代码行数:36,代码来源:TimedCounterAggregatorBlockFactory.cs

示例12: ImbleWatcher

        public ImbleWatcher()
        {
            this.watcher = new BluetoothLEAdvertisementWatcher();
            this.watcher.ScanningMode = BluetoothLEScanningMode.Active;     // We have to perform active scanning to check scan responses from devices.
            this.resetSubject = new Subject<Unit>().AddTo(this.disposables);
            
            var candidateAddresses = new ConcurrentDictionary<ulong, ulong>();
            var resetObservable = this.resetSubject
                .Do(_ => candidateAddresses.Clear());

            var receivedObservable = Observable.FromEvent<TypedEventHandler<BluetoothLEAdvertisementWatcher, BluetoothLEAdvertisementReceivedEventArgs>, BluetoothLEAdvertisementReceivedEventArgs>(
                handler => (sender, args) => handler(args),
                handler => this.watcher.Received += handler,
                handler => this.watcher.Received -= handler)
                .Publish();

            // Check scan responses and add their address to the candidate device list if they contains the target service UUID as Service Solicitation data.
            receivedObservable
                .Where(args => args.AdvertisementType.HasFlag(BluetoothLEAdvertisementType.ScanResponse))
                .Where(args => args.Advertisement.DataSections.Any(section => MatchSolicitationServiceLong(section, ImbleDevice.ServiceUuid)))
                .Subscribe(args => candidateAddresses.TryAdd(args.BluetoothAddress, args.BluetoothAddress))
                .AddTo(this.disposables);

            // Check advertisement data 
            this.UnconnectedDevices = receivedObservable
                .Where(args => !args.AdvertisementType.HasFlag(BluetoothLEAdvertisementType.ScanResponse))
                .Where(args => candidateAddresses.ContainsKey(args.BluetoothAddress))
                .Distinct(args => args.BluetoothAddress)
                .Select(args => new UnconnectedImbleDevice(args.BluetoothAddress, args.Advertisement, args.RawSignalStrengthInDBm))
                .ToReadOnlyReactiveCollection(resetObservable)
                .AddTo(this.disposables);

            receivedObservable.Connect().AddTo(this.disposables);

            this.watcher.Start();
        }
开发者ID:ciniml,项目名称:ImbleCommunication,代码行数:36,代码来源:ImbleWatcher.cs

示例13: Close

        public void Close()
        {
            IsOpen = false;
            var connections = _fdbConnections;
            _fdbConnections = new ConcurrentDictionary<int, IntPtr>();
            foreach(var ptr in connections) {
                ForestDBBridge.Check(err => Native.c4db_close((C4Database*)ptr.Value.ToPointer(), err));
            }

            _fdbConnections.Clear();
        }
开发者ID:Steven-Mark-Ford,项目名称:couchbase-lite-net,代码行数:11,代码来源:ForestDBCouchStore.cs

示例14: UpdateBlocksToNearbyPlayers

        protected override void UpdateBlocksToNearbyPlayers(object state)
        {
            BlocksUpdateLock.EnterWriteLock();
            int num = Interlocked.Exchange(ref NumBlocksToUpdate, 0);
            ConcurrentDictionary<short, short> temp = BlocksToBeUpdated;
            BlocksToBeUpdated = BlocksUpdating;
            BlocksUpdateLock.ExitWriteLock();

            BlocksUpdating = temp;

            if (num == 1)
            {
                short keyCoords = BlocksUpdating.Keys.First();
                short index;
                BlocksUpdating.TryGetValue(keyCoords, out index);
                int worldX = (X << 4) + (index >> 12 & 0xf);
                int worldY = (index & 0xff);
                int worldZ = (Z << 4) + (index >> 8 & 0xf);
                byte blockId = World.GetBlockId(worldX, worldY, worldZ);
                byte data = World.GetBlockData(worldX, worldY, worldZ);

                SendPacketToAllNearbyPlayers(new BlockChangePacket
                {X = worldX, Y = (sbyte) worldY, Z = worldZ, Data = data, Type = blockId});

            }
            else if (num < 20)
            {
                sbyte[] data = new sbyte[num];
                sbyte[] types = new sbyte[num];
                short[] blocks = new short[num];

                int count = 0;
                foreach (short key in BlocksUpdating.Keys)
                {
                    short index;
                    BlocksUpdating.TryGetValue(key, out index);
                    int worldX = (X << 4) + (index >> 12 & 0xf);
                    int worldY = (index & 0xff);
                    int worldZ = (Z << 4) + (index >> 8 & 0xf);

                    data[count] = (sbyte)World.GetBlockData(worldX, worldY, worldZ);
                    types[count] = (sbyte)World.GetBlockId(worldX, worldY, worldZ);
                    blocks[count] = index;
                }
                SendPacketToAllNearbyPlayers(new MultiBlockChangePacket { Coords = blocks, Metadata = data, Types = types, X = this.X, Z = this.Z});
            }
            else
            {
                SendPacketToAllNearbyPlayers(new MapChunkPacket { Chunk = this });
            }

            BlocksUpdating.Clear();
            base.UpdateBlocksToNearbyPlayers(state);
        }
开发者ID:AVATAR-Phoenix,项目名称:c-raft,代码行数:54,代码来源:Chunk.cs

示例15: ActiveTrips

 public ActiveTrips(string id)
 {
     dict = new ConcurrentDictionary<string, Trip>();
     dict.Clear();
     var lastDbTripId = StorageManager.GetLastTripId();
     this.lastID = lastDbTripId;
 }
开发者ID:TripThru,项目名称:Gateway,代码行数:7,代码来源:Gateway.cs


注:本文中的ConcurrentDictionary.Clear方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。