本文整理汇总了C#中ConcurrentDictionary.TryGetValue方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentDictionary.TryGetValue方法的具体用法?C# ConcurrentDictionary.TryGetValue怎么用?C# ConcurrentDictionary.TryGetValue使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentDictionary
的用法示例。
在下文中一共展示了ConcurrentDictionary.TryGetValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Resolve
public bool Resolve(ConcurrentDictionary<int, IPersistIfcEntity> references)
{
IPersistIfcEntity entity;
if (references.TryGetValue(ReferenceEntityLabel, out entity))
{
PropertyValue pv = new PropertyValue();
pv.Init(entity);
try
{
ReferencingEntity.IfcParse(ReferencingPropertyId, pv);
return true;
}
catch (Exception)
{
IfcType ifcType = IfcMetaData.IfcType(ReferencingEntity);
XbimModel.Logger.ErrorFormat("Data Error. Cannot set the property = {0} of entity #{1} = {2} to entity #{3}, schema violation. Ignored",
ifcType.IfcProperties[ReferencingPropertyId+1].PropertyInfo.Name,
ReferencingEntity.EntityLabel,
ReferencingEntity.GetType().Name,
ReferenceEntityLabel);
return false;
}
}
else
return false;
}
示例2: TryGetValue_ReturnsNoValue_WhenItemDoesNotExist
public void TryGetValue_ReturnsNoValue_WhenItemDoesNotExist()
{
var dict = new ConcurrentDictionary<String, String>();
var result = dict.TryGetValue("Test");
Assert.IsFalse(result.HasValue);
}
示例3: BrokenConcurrentDictionary
public static void BrokenConcurrentDictionary () {
const string msg = "Broken ConcurrentDictionary: https://bugzilla.xamarin.com/show_bug.cgi?id=6225";
var keyA = new MyKey(1);
var keyB = new MyKey(1);
var dict = new ConcurrentDictionary<MyKey, string>(1, 2);
if (!dict.TryAdd(keyA, "a"))
Fail(msg);
string foundValue;
if (!dict.TryGetValue(keyA, out foundValue) || foundValue != "a")
Fail(msg);
if (dict.TryGetValue(keyB, out foundValue))
Fail(msg);
}
示例4: BuildingMenuBar
/// <summary>
/// Constructor
/// </summary>
/// <param name="textureCache"></param>
public BuildingMenuBar(ConcurrentDictionary<string, Texture2D> textureCache)
{
this.textureCache = textureCache;
position = new Vector2(0, 0);
Texture2D mbB;
textureCache.TryGetValue("MenuBarEnding", out mbB);
mbBegin = new Tile(mbB, 120);
mbEnd = new Tile(mbB, 120);
mbEnd.Rotate(180);
Texture2D mbM;
textureCache.TryGetValue("MenuBar", out mbM);
mbMiddle = new Tile(mbM, 120);
buildthings.Add(new Tile(textureCache, 100, "WoodWall"));
buildthings.Add(new Tile(textureCache, 100, "WoodWallCorner"));
buildthings.Add(new Tile(textureCache, 100, "Stone"));
selector = new Tile(textureCache, 100, "BuildCursor");
}
示例5: Set
static void Set(ConcurrentDictionary<Type,ConcurrentDictionary<Type,LambdaInfo>> expressions, Type from, Type to, LambdaInfo expr)
{
ConcurrentDictionary<Type,LambdaInfo> dic;
if (!expressions.TryGetValue(from, out dic))
expressions[from] = dic = new ConcurrentDictionary<Type, LambdaInfo>();
dic[to] = expr;
}
示例6: StreamNotificationCommands
public StreamNotificationCommands()
{
checkTimer = new Timer(async (state) =>
{
oldCachedStatuses = new ConcurrentDictionary<string, StreamStatus>(cachedStatuses);
cachedStatuses = new ConcurrentDictionary<string, StreamStatus>();
try
{
IEnumerable<FollowedStream> streams;
using (var uow = DbHandler.UnitOfWork())
{
streams = uow.GuildConfigs.GetAllFollowedStreams();
}
foreach (var stream in streams)
{
StreamStatus data;
try
{
data = await GetStreamStatus(stream).ConfigureAwait(false);
if (data == null)
return;
}
catch
{
continue;
}
StreamStatus oldData;
oldCachedStatuses.TryGetValue(data.Link, out oldData);
if (oldData == null || data.IsLive != oldData.IsLive)
{
if (FirstPass)
continue;
var server = NadekoBot.Client.GetGuild(stream.GuildId);
var channel = server?.GetTextChannel(stream.ChannelId);
if (channel == null)
continue;
var msg = $"`{stream.Username}`'s stream is now " +
$"**{(data.IsLive ? "ONLINE" : "OFFLINE")}** with " +
$"**{data.Views}** viewers.";
if (data.IsLive)
if (stream.Type == FollowedStream.FollowedStreamType.Hitbox)
msg += $"\n`Here is the Link:`【 http://www.hitbox.tv/{stream.Username}/ 】";
else if (stream.Type == FollowedStream.FollowedStreamType.Twitch)
msg += $"\n`Here is the Link:`【 http://www.twitch.tv/{stream.Username}/ 】";
else if (stream.Type == FollowedStream.FollowedStreamType.Beam)
msg += $"\n`Here is the Link:`【 http://www.beam.pro/{stream.Username}/ 】";
try { await channel.SendMessageAsync(msg).ConfigureAwait(false); } catch { }
}
}
FirstPass = false;
}
catch { }
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(60));
}
示例7: TryGetValue_ReturnsValue_WithItemExists
public void TryGetValue_ReturnsValue_WithItemExists()
{
var dict = new ConcurrentDictionary<String, String>();
dict.TryAdd("Test", "Hello, World!");
var result = dict.TryGetValue("Test");
Assert.IsTrue(result.HasValue);
Assert.AreEqual("Hello, World!", result.Value);
}
示例8: Test
public unsafe void Test()
{
Action<ConcurrentDictionary<ulong, ulong>, ulong, ulong> action = (map, first, count) =>
{
var watch = Stopwatch.StartNew();
for (var i = first; i < first + count; i++)
{
if (!map.TryAdd(i, i))
{
throw new Exception("Failed to insert " + i);
}
ulong val;
if (!map.TryGetValue(i, out val))
{
throw new Exception("Failed to validate at " + i);
}
//Console.WriteLine("Added {0} at {1}", val, i);
}
watch.Stop();
Console.WriteLine("Elapsed: {0}, for {1}, {2}", watch.ElapsedMilliseconds, first, count);
};
{
var dict = new ConcurrentDictionary<ulong, ulong>();
ulong nThreads = 4;
ulong count = 1000000;
MultiThread(action, dict, (int)nThreads, count);
for (ulong i = 1; i < 1 + nThreads * count; i++)
{
ulong val;
if (!dict.TryGetValue(i, out val))
{
throw new Exception(string.Format("Failed to get at {0}", i));
}
if (val != i)
{
throw new Exception(string.Format("Failed at {0} with {1}", i, val));
}
}
dict = null;
GC.Collect(2, GCCollectionMode.Forced);
GC.Collect(2, GCCollectionMode.Forced);
GC.Collect(2, GCCollectionMode.Forced);
GC.Collect(2, GCCollectionMode.Forced);
Console.WriteLine("Completed test");
Console.ReadLine();
}
}
示例9: GetCurrentGenerator
private static Generator GetCurrentGenerator(ConcurrentDictionary<int, Generator> dict, int managedThreadId)
{
Generator result;
if (!dict.TryGetValue(managedThreadId, out result))
{
result = new Generator(new QrEncoder());
dict.AddOrUpdate(managedThreadId, result, (_, __) => result);
}
return result;
}
示例10: TransferContent
private static void TransferContent(ConcurrentDictionary<string, int> input, BlockingCollection<Info> output)
{
foreach (var word in input.Keys)
{
int value;
if (input.TryGetValue(word, out value))
{
output.Add(new Info { Word = word, Count = value });
}
}
}
示例11: CompositeModelFactory
public CompositeModelFactory(IEnumerable<IModelFactory> modelFactories)
{
_modelFactories = new ConcurrentDictionary<Type, IModelFactory>();
foreach (var modelFactory in modelFactories)
{
foreach (var supportedType in modelFactory.GetSupportedTypes())
{
IModelFactory existingModelFactory;
if (_modelFactories.TryGetValue(supportedType, out existingModelFactory))
throw new InvalidOperationException("The model type '" + supportedType + "' is already supported by " + existingModelFactory.GetType());
_modelFactories[supportedType] = modelFactory;
}
}
}
示例12: ToMatrix3D
/// <summary>
/// Builds a windows XbimMatrix3D from a CartesianTransformationOperator3DnonUniform
/// </summary>
/// <param name = "ct3D"></param>
/// <returns></returns>
public static XbimMatrix3D ToMatrix3D(this IfcCartesianTransformationOperator3DnonUniform ct3D, ConcurrentDictionary<int, Object> maps = null)
{
if (maps == null)
return ConvertCartesianTransformationOperator3DnonUniform(ct3D);
else
{
object transform;
if (maps.TryGetValue(Math.Abs(ct3D.EntityLabel), out transform)) //already converted it just return cached
return (XbimMatrix3D)transform;
XbimMatrix3D matrix = ConvertCartesianTransformationOperator3DnonUniform(ct3D);
maps.TryAdd(Math.Abs(ct3D.EntityLabel), matrix);
return matrix;
}
}
示例13: Execute
public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context)
{
IRazorPageFactory pageFactory = new VirtualPathRazorPageFactory(context.InputFolder, context, _basePageType);
List<IDocument> validInputs = inputs
.Where(x => _ignorePrefix == null || !x.ContainsKey("SourceFileName") || !x.String("SourceFileName").StartsWith(_ignorePrefix))
.ToList();
// Compile the pages in parallel
ConcurrentDictionary<IDocument, Tuple<ViewContext, ViewEngineResult>> compilationResults
= new ConcurrentDictionary<IDocument, Tuple<ViewContext, ViewEngineResult>>();
Parallel.ForEach(validInputs, x =>
{
context.Trace.Verbose("Compiling Razor for {0}", x.Source);
IViewStartProvider viewStartProvider = new ViewStartProvider(pageFactory, _viewStartPath?.Invoke(x));
IRazorViewFactory viewFactory = new RazorViewFactory(viewStartProvider);
IRazorViewEngine viewEngine = new RazorViewEngine(pageFactory, viewFactory);
ViewContext viewContext = new ViewContext(null, new ViewDataDictionary(), null, x.Metadata, context, viewEngine);
ViewEngineResult viewEngineResult;
using (Stream stream = x.GetStream())
{
viewEngineResult = viewEngine.GetView(viewContext, GetRelativePath(x), stream).EnsureSuccessful();
}
compilationResults[x] = new Tuple<ViewContext, ViewEngineResult>(viewContext, viewEngineResult);
});
// Now evaluate them in sequence - have to do this because BufferedHtmlContent doesn't appear to work well in multi-threaded parallel execution
TaskScheduler exclusiveScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler;
CancellationToken cancellationToken = new CancellationToken();
return validInputs
.Select(x =>
{
using (context.Trace.WithIndent().Verbose("Processing Razor for {0}", x.Source))
{
Tuple<ViewContext, ViewEngineResult> compilationResult;
if (compilationResults.TryGetValue(x, out compilationResult))
{
using (StringWriter writer = new StringWriter())
{
compilationResult.Item1.View = compilationResult.Item2.View;
compilationResult.Item1.Writer = writer;
Task.Factory.StartNew(() => compilationResult.Item2.View.RenderAsync(compilationResult.Item1),
cancellationToken, TaskCreationOptions.None, exclusiveScheduler).Unwrap().GetAwaiter().GetResult();
return x.Clone(writer.ToString());
}
}
context.Trace.Warning("Could not find compilation result for {0}", x.Source);
return null;
}
});
}
示例14: ToMatrix3D
/// <summary>
/// Converts an Axis2Placement3D to a windows XbimMatrix3D
/// </summary>
/// <param name = "axis3"></param>
/// <returns></returns>
public static XbimMatrix3D ToMatrix3D(this IfcAxis2Placement3D axis3, ConcurrentDictionary<int, Object> maps = null)
{
if (maps == null)
return ConvertAxis3D(axis3);
else
{
object transform;
if (maps != null && maps.TryGetValue(axis3.EntityLabel, out transform)) //already converted it just return cached
return (XbimMatrix3D)transform;
transform = ConvertAxis3D(axis3);
if (maps != null) maps.TryAdd(axis3.EntityLabel, transform);
return (XbimMatrix3D)transform;
}
}
示例15: IsGeneratedDocument
/// <summary>
/// Checks whether the given document is auto generated by a tool
/// (based on filename or comment header).
/// </summary>
/// <remarks>
/// <para>The exact conditions used to identify generated code are subject to change in future releases. The current algorithm uses the following checks.</para>
/// <para>Code is considered generated if it meets any of the following conditions.</para>
/// <list type="bullet">
/// <item>The code is contained in a file which starts with a comment containing the text
/// <c><auto-generated</c>.</item>
/// <item>The code is contained in a file with a name matching certain patterns (case-insensitive):
/// <list type="bullet">
/// <item>*.designer.cs</item>
/// </list>
/// </item>
/// </list>
/// </remarks>
/// <param name="tree">The syntax tree to examine.</param>
/// <param name="cache">The concurrent results cache.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
/// <returns>
/// <para><see langword="true"/> if <paramref name="tree"/> is located in generated code; otherwise,
/// <see langword="false"/>. If <paramref name="tree"/> is <see langword="null"/>, this method returns
/// <see langword="false"/>.</para>
/// </returns>
public static bool IsGeneratedDocument(this SyntaxTree tree, ConcurrentDictionary<SyntaxTree, bool> cache, CancellationToken cancellationToken)
{
if (tree == null)
{
return false;
}
bool result;
if (cache.TryGetValue(tree, out result))
{
return result;
}
bool generated = IsGeneratedDocumentNoCache(tree, cancellationToken);
cache.TryAdd(tree, generated);
return generated;
}