本文整理汇总了C#中ConcurrentDictionary.TryAdd方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentDictionary.TryAdd方法的具体用法?C# ConcurrentDictionary.TryAdd怎么用?C# ConcurrentDictionary.TryAdd使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentDictionary
的用法示例。
在下文中一共展示了ConcurrentDictionary.TryAdd方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CustomerService
static CustomerService()
{
customers = new ConcurrentDictionary<int,Customer>();
customers.TryAdd(1, new Customer() { Id = 1, Name = "Customer1" });
customers.TryAdd(2, new Customer() { Id = 2, Name = "Customer2" });
customers.TryAdd(3, new Customer() { Id = 3, Name = "Customer3" });
}
示例2: Encode
public void Encode()
{
LogManager.SetupLogManager();
var log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod());
log.Info("Start");
//Dictionary<string, string> obj;
//obj = new Dictionary<string, string> {{"a", "b"}};
//var imObj = ImmutableDictionary.Create<string, string>().AddRange(obj);
var imObj = new ConcurrentDictionary<string, string>();
imObj.TryAdd("a","b");
Assert.Equal(ParseQS.Encode(imObj), "a=b");
//obj = new Dictionary<string, string> {{"a", "b"}, {"c", "d"}};
//imObj = ImmutableDictionary.Create<string, string>().AddRange(obj);
imObj = new ConcurrentDictionary<string, string>();
imObj.TryAdd("a", "b");
imObj.TryAdd("c", "d");
Assert.Equal(ParseQS.Encode(imObj), "a=b&c=d");
//obj = new Dictionary<string, string> {{"a", "b"}, {"c", "tobi rocks"}};
//imObj = ImmutableDictionary.Create<string, string>().AddRange(obj);
imObj = new ConcurrentDictionary<string, string>();
imObj.TryAdd("a", "b");
imObj.TryAdd("c", "tobi rocks");
Assert.Equal(ParseQS.Encode(imObj), "a=b&c=tobi%20rocks");
}
示例3: Test
public void Test()
{
var keyValues = new Dictionary<string, string>();
using (var cluster = new Cluster())
{
using (var bucket = cluster.OpenBucket())
{
for (int i = 0; i <10; i++)
{
var key = "MGETKEY" + i;
var value = "{\"val:\"MGETVALUE" + i +"\"}";
bucket.Upsert(key, value);
keyValues.Add(key, value);
}
foreach (var keyValue in keyValues)
{
Console.WriteLine(bucket.Get<dynamic>(keyValue.Key).Value);
}
}
}
var operations = new ConcurrentDictionary<uint, IOperation>();
foreach (var keyValue in keyValues)
{
var getk = new GetK<dynamic>(keyValue.Key, GetVBucket(), Converter, Transcoder);
operations.TryAdd(getk.Opaque, getk);
}
var noop = new Noop(Converter);
operations.TryAdd(noop.Opaque, noop);
var results = IOStrategy.Execute<dynamic>(operations);
}
示例4: Store
/// <summary>
/// Store build outputs in the cache by reading them from the file system
/// </summary>
/// <param name="builder">Builder key (first part of the key)</param>
/// <param name="fingerprint">Dependency fingerprint created when the builder was executed (second part of the key)</param>
/// <param name="outputs">Target-relative path of the build outputs to be cached</param>
/// <param name="targetRoot">File system abstraction of the root target directory</param>
public void Store(BuildKey builder, IDependencyFingerprint fingerprint, IEnumerable<TargetRelativePath> outputs, IFileSystemDirectory targetRoot)
{
MemoryCacheItem item = GetOrCreate(builder);
var map = new ConcurrentDictionary<TargetRelativePath, byte[]>();
Parallel.ForEach(outputs, outputPath =>
{
if (targetRoot.Exists(outputPath))
{
using (var stream = targetRoot.ReadBinaryFile(outputPath))
{
var buf = new byte[stream.Length];
stream.Read(buf, 0, buf.Length);
map.TryAdd(outputPath, buf);
}
}
else
{
map.TryAdd(outputPath, null);
}
});
item.Update(fingerprint, map);
}
示例5: ArticlesController
static ArticlesController()
{
database = new ConcurrentDictionary<int, Article>();
database.TryAdd(1, new Article { Id = 1, Name = "Super lecker Pudding", Description = "Blaaa blaaa blubbb"});
database.TryAdd(2, new Article { Id = 2, Name = "Mjamm-mjamm Gurken", Description = "Yadda yadda yad"});
database.TryAdd(3, new Article { Id = 3, Name = "Mhhhh Salzstangen", Description = "Momm momm mom" });
}
示例6: CycleIsCollidingInBounds
public void CycleIsCollidingInBounds()
{
var gameConfig = new GameConfiguration(new CycleConfiguration(), new MapConfiguration());
var map = new Map(gameConfig.MapConfig);
var startPosition = new Vector3(0, gameConfig.CycleConfig.Y_OFFSET, 0);
var cycle = new Cycle(1, startPosition, new Vector3(1, 0, 0), Math.PI + Math.PI * .5, 0xff0000, map, gameConfig);
var cycle2 = new Cycle(2, startPosition, new Vector3(1, 0, 0), Math.PI + Math.PI * .5, 0xff0000, map, gameConfig);
var collisionChecker = new CollisionChecker(map);
var startLocation = map.Utilities.ToMapLocation(startPosition);
var cycles = new ConcurrentDictionary<long, Cycle>();
cycles.TryAdd(cycle.ID, cycle);
cycles.TryAdd(cycle2.ID, cycle2);
map.RegisterCycles(cycles);
map[startLocation] = 2;
collisionChecker.ValidateCollision(cycle);
Assert.True(cycle.Colliding);
map.Clear();
cycle.Colliding = false;
map[startLocation] = -cycle.ID;
collisionChecker.ValidateCollision(cycle);
Assert.False(cycle.Colliding);
map.Clear();
cycle.Colliding = false;
map[startLocation] = 0;
collisionChecker.ValidateCollision(cycle);
Assert.False(cycle.Colliding);
}
示例7: GetImageWithDisplacement
public ReturnImage GetImageWithDisplacement(FastBitmap currFrame, FastBitmap nextFrame, List<Point> edgePoints)
{
_nBytesPerPixel = currFrame.CCount;
currFrame.LockBits();
nextFrame.LockBits();
byte[] currRgbValues = currFrame.Pixels;
byte[] nextRgbValues = nextFrame.Pixels;
ConcurrentDictionary<Point, Point> displacements = new ConcurrentDictionary<Point, Point>();
Parallel.ForEach(edgePoints, (edgePoint) =>
{
int edgePointPos;
List<Color> pointVicinity = GetPointVicinity(edgePoint, currRgbValues, currFrame.Width, currFrame.Height, currFrame.Stride, out edgePointPos);
_brief = new BRIEF((POINT_WINDOW_SIDE + 1) * (POINT_WINDOW_SIDE + 1), edgePointPos);
string vicinityDescriptor = _brief.GetImageDescriptor(pointVicinity);
if (pointVicinity[edgePointPos] != Color.Black)
{
Point nextFramePoint = FindPointDiscplacement(edgePoint, nextRgbValues, nextFrame.Width, nextFrame.Height, vicinityDescriptor, nextFrame.Stride, pointVicinity[edgePointPos]);
displacements.TryAdd(edgePoint, nextFramePoint);
}
else
displacements.TryAdd(edgePoint, edgePoint);
});
currFrame.UnlockBits();
nextFrame.UnlockBits();
Frame frame = GetFrameByChanell(currFrame, displacements);
//frames.Add();
ReturnImage image = new ReturnImage(frame, currFrame);
return image;
}
示例8: create
/// <summary>
/// Create a collection of items, 4 to be precisely
/// </summary>
public static void create()
{
int initialCapacity = 4;
// The higher the concurrencyLevel, the higher the theoretical number of operations
// that could be performed concurrently on the ConcurrentDictionary. However, global
// operations like resizing the dictionary take longer as the concurrencyLevel rises.
// For the purposes of this example, we'll compromise at numCores * 2.
int numProcs = Environment.ProcessorCount;
int concurrencyLevel = numProcs * 2;
// Construct the dictionary with the desired concurrencyLevel and initialCapacity
Items = new ConcurrentDictionary<int, Item>(concurrencyLevel, initialCapacity);
Items.TryAdd(0, new Item { Order = 0, Description = "Description of the first Item", Title = "first", Image = "img01.jpg" });
Items.TryAdd(1, new Item { Order = 1, Description = "Description of the second Item", Title = "second", Image = "img02.jpg" });
Items.TryAdd(2, new Item { Order = 2, Description = "Description of the third Item", Title = "third", Image = "img03.jpg" });
Items.TryAdd(3, new Item { Order = 3, Description = "Description of the fourth Item", Title = "fourth", Image = "img04.jpg" });
//An enumerator remains valid as long as the collection remains unchanged.
//If changes are made to the collection, such as adding, modifying, or deleting elements,
//the enumerator is irrecoverably invalidated and its behavior is undefined.
//The enumerator does not have exclusive access to the collection; therefore,
//enumerating through a collection is intrinsically not a thread-safe procedure.
//Items = new List<Item>{ new Item { Order =0, Description ="Description of the first Item", Title ="first", Image ="img01.jpg"},
// new Item { Order =1, Description ="Description of the second Item", Title ="second", Image ="img02.jpg"},
// new Item { Order =2, Description ="Description of the third Item", Title ="third", Image ="img03.jpg"},
// new Item { Order =3, Description ="Description of the fourth Item", Title ="fourth", Image ="img04.jpg"}};
}
示例9: ProductsController
static ProductsController()
{
database = new ConcurrentDictionary<int, Product>();
database.TryAdd(1, new Product { Id = 1, Title = "Super lecker Pudding", Description = "Blaaa blaaa blubbb", Amount = 8 });
database.TryAdd(2, new Product { Id = 2, Title = "Mjamm-mjamm Gurken", Description = "Yadda yadda yad", Amount = 149 });
database.TryAdd(3, new Product { Id = 3, Title = "Mhhhh Salzstangen", Description = "Momm momm mom", Amount = 53 });
}
示例10: Main
public static void Main()
{
var stock = new ConcurrentDictionary<string, int>();
stock.TryAdd("jDays", 4);
stock.TryAdd("technologyhour", 3);
Console.WriteLine("No. of shirts in stock = {0}", stock.Count);
var success = stock.TryAdd("pluralsight", 6);
Console.WriteLine("Added succeeded? " + success);
success = stock.TryAdd("pluralsight", 6);
Console.WriteLine("Added succeeded? " + success);
stock["buddhistgeeks"] = 5;
//stock["pluralsight"]++; <-- not thread safe two instructions
var psStock = stock.AddOrUpdate("pluralsight", 1, (key, oldValue) => oldValue + 1);
Console.WriteLine("pluralsight new value = {0}", psStock);
Console.WriteLine("stock[pluralsight] = {0}", stock.GetOrAdd("pluralsight", 0));
int jDaysValue;
success= stock.TryRemove("jDays", out jDaysValue);
if (success) Console.WriteLine("Value removed was: " + jDaysValue);
Console.WriteLine("\r\nEnumerating:");
foreach (var keyValuePair in stock)
{
Console.WriteLine("{0}: {1}", keyValuePair.Key, keyValuePair.Value);
}
}
示例11: SqlClientEncryptionAlgorithmFactoryList
private SqlClientEncryptionAlgorithmFactoryList () {
_encryptionAlgoFactoryList = new ConcurrentDictionary<string, SqlClientEncryptionAlgorithmFactory>(concurrencyLevel: 4 * Environment.ProcessorCount /* default value in ConcurrentDictionary*/, capacity: 2);
// Add wellknown algorithms
_encryptionAlgoFactoryList.TryAdd(SqlAeadAes256CbcHmac256Algorithm.AlgorithmName, new SqlAeadAes256CbcHmac256Factory());
_encryptionAlgoFactoryList.TryAdd(SqlAes256CbcAlgorithm.AlgorithmName, new SqlAes256CbcFactory());
}
示例12: BulkGetBondStaticDataFromCarbon
private static IReadOnlyDictionary<string, AnalyticsBondStaticData> BulkGetBondStaticDataFromCarbon(ICarbonClient client,
IReadOnlyCollection<string> bondIds)
{
if (bondIds == null || bondIds.Count == 0) return new Dictionary<string, AnalyticsBondStaticData>();
var dict = new ConcurrentDictionary<string, AnalyticsBondStaticData>();
var ids = new List<string>();
foreach (var id in bondIds)
{
AnalyticsBondStaticData data;
if (BondStaticDataCache.TryGetValue(id, out data))
{
dict.TryAdd(id, data);
}
else
{
var carbonBond = client.GetCachedCarbonBond(id);
if (carbonBond == null)
{
ids.Add(id);
}
else
{
var bond = ConvertCarbonBondToAnalyticsBondStaticData(carbonBond);
if (bond != null)
{
dict.TryAdd(id, bond);
BondStaticDataCache.TryAdd(id, bond);
BondStaticDataCache.TryAdd(bond.Id, bond);
}
else
{
ids.Add(id);
}
}
}
}
if (ids.Count == 0) return dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
var datas = client.BulkGetSecurityMetadataInternal(ids, "static-bond");
if (datas == null || datas.Count == 0) return dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Parallel.ForEach(datas, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
data =>
{
var bond = ConvertCarbonBondStaticToAnalyticBondStatic(client, data);
if (bond != null)
{
BondStaticDataCache.TryAdd(bond.Id, bond);
BondStaticDataCache.TryAdd(data.Identifier, bond);
dict.TryAdd(bond.Id, bond);
}
});
return dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
示例13: AddEvent_should_fill_in_zero_events_if_key_points_to_an_out_of_bounds_index
public void AddEvent_should_fill_in_zero_events_if_key_points_to_an_out_of_bounds_index()
{
var eventStore = new ConcurrentDictionary<int, int>();
eventStore.TryAdd(0, 1);
eventStore.TryAdd(1, 2);
_monitor.AddEvent(eventStore, 10);
var expected = new[] {1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1};
eventStore.Values.ShouldAllBeEquivalentTo(expected);
}
示例14: PopulateTestData
private static TestData PopulateTestData(bool populateAll)
{
//Define Defaults
var defineDefaults = new Mock<ISetupMonitorConfig>();
defineDefaults.Setup(x => x.CreateDefaultReduceLevels(It.IsAny<MonitorConfig>(), It.IsAny<List<ReduceLevel>>(), It.IsAny<IDbConnection>())).Verifiable();
//Cache
var monitorInfoDictionary = new ConcurrentDictionary<string, MonitorInfo>();
var monitorConfigsDictionary = new ConcurrentDictionary<string, MonitorConfig>();
var reductionLevel = new ReduceLevel { Resolution = 1000 };
var monitorConfig = new MonitorConfig { Name = "Test", ReduceLevels = new List<ReduceLevel> { reductionLevel } };
var monitorInfo = new MonitorInfo { TablesCreated = false, MonitorRecords = new List<MonitorRecord<double>> { new MonitorRecord<double>(DateTime.Now, 5) }, MonitorConfig = monitorConfig };
monitorInfoDictionary.TryAdd("Test", monitorInfo);
monitorConfigsDictionary.TryAdd("Test", monitorConfig);
reductionLevel = new ReduceLevel { Resolution = 1000 };
monitorConfig = new MonitorConfig { Name = "Jester", ReduceLevels = new List<ReduceLevel> { reductionLevel } };
monitorInfo = new MonitorInfo { TablesCreated = false, MonitorRecords = new List<MonitorRecord<double>> { new MonitorRecord<double>(DateTime.Now, 5) }, MonitorConfig = monitorConfig };
monitorInfoDictionary.TryAdd("Jester", monitorInfo);
monitorConfigsDictionary.TryAdd("Jester", monitorConfig);
var cache = new Mock<IDataCache>();
cache.SetupGet(x => x.MonitorInfo).Returns(monitorInfoDictionary);
cache.SetupGet(x => x.MonitorConfigs).Returns(monitorConfigsDictionary);
//Storage
var storage = new Mock<IStorageCommands>();
storage.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<IEnumerable<MonitorRecord<double>>>(), It.IsAny<IDbConnection>(), It.IsAny<IDbTransaction>())).Verifiable();
//Logic
var logic = new Mock<IRecordFlushUpdate>();
logic.Setup(x => x.UpdateExisting(It.IsAny<string>(), It.IsAny<SortedDictionary<long, MonitorRecord<double>>>(), It.IsAny<IDbConnection>(), It.IsAny<IDbTransaction>())).Verifiable();
//Db Provider
var transaction = new Mock<IDbTransaction>();
transaction.SetupGet(x => x.IsolationLevel).Returns(IsolationLevel.Serializable).Verifiable();
transaction.Setup(x => x.Rollback()).Verifiable();
transaction.Setup(x => x.Commit()).Verifiable();
var connection = new Mock<IDbConnection>();
connection.Setup(x => x.Open()).Verifiable();
connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object).Verifiable();
connection.Setup(x => x.BeginTransaction(It.IsAny<IsolationLevel>())).Returns(transaction.Object).Verifiable();
var dbProviderFactory = new Mock<IStorageFactory>();
dbProviderFactory.Setup(x => x.CreateConnection()).Returns(connection.Object).Verifiable();
//Settings
var settings = BuildSettings();
return new TestData { Settings = settings, Cache = cache, DbProviderFactory = dbProviderFactory, Logic = logic, Storage = storage, Transaction = transaction, Connection = connection, DefineDefaults = defineDefaults };
}
示例15: CreateMediaTypeMap
private static ConcurrentDictionary<string, MediaTypeHeaderValue> CreateMediaTypeMap()
{
var dictionary = new ConcurrentDictionary<string, MediaTypeHeaderValue>(StringComparer.OrdinalIgnoreCase);
dictionary.TryAdd(".js", MediaTypeHeaderValue.Parse("application/javascript"));
dictionary.TryAdd(".json", MediaTypeHeaderValue.Parse("application/json"));
// Add media type for markdown
dictionary.TryAdd(".md", MediaTypeHeaderValue.Parse("text/plain"));
return dictionary;
}