本文整理汇总了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;
}
示例2: DebuggerDecompilerService
static DebuggerDecompilerService()
{
DebugInformation = new ConcurrentDictionary<int, DecompileInformation>();
ProjectService.SolutionClosed += delegate {
DebugInformation.Clear();
GC.Collect();
};
}
示例3: ObjectBaseValidator
static ObjectBaseValidator()
{
Cache = new ConcurrentDictionary<Type, ObjectBaseValidator>();
DxSettings.GlobalSettings.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == "CacheTypeCheckers" && !DxSettings.GlobalSettings.CacheTypeCheckers)
Cache.Clear();
};
}
示例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;
}
示例5: PlatformFactory
static PlatformFactory()
{
HelperCache = new ConcurrentDictionary<string, HelperBase>();
//添加监听
ConfigManager.Change += file =>
{
if (file == ConfigUtils<PlatformConfig>.Instance.FileName)
{
HelperCache.Clear();
}
};
}
示例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;
}
示例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);
}
示例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;
}
示例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;
}
示例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();
}
示例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;
}
示例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();
}
示例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();
}
示例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);
}
示例15: ActiveTrips
public ActiveTrips(string id)
{
dict = new ConcurrentDictionary<string, Trip>();
dict.Clear();
var lastDbTripId = StorageManager.GetLastTripId();
this.lastID = lastDbTripId;
}