Example #1
0
        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);
        }
        public void TryGetValue_ReturnsNoValue_WhenItemDoesNotExist()
        {
            var dict = new ConcurrentDictionary<String, String>();
            var result = dict.TryGetValue("Test");

            Assert.IsFalse(result.HasValue);
        }
Example #3
0
        /// <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");
        }
Example #4
0
		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;
		}
            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));
            }
        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);
        }
        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();
            }
        }
Example #8
0
        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;
        }
Example #9
0
    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 });
        }
	    }
    }
 /// <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;
     }
 }
 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;
         }
     }
 }
Example #12
0
        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;
                    }
                });
        }
 /// <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;
     }
     
 }
 public static XbimMatrix3D ToMatrix3D(this IfcAxis2Placement2D axis2, ConcurrentDictionary<int, Object> maps = null)
 {
     object transform;
     if (maps != null && maps.TryGetValue(axis2.EntityLabel, out transform)) //already converted it just return cached
         return (XbimMatrix3D)transform;
     if (axis2.RefDirection != null)
     {
         XbimVector3D v = axis2.RefDirection.XbimVector3D();
         v.Normalize();
         transform = new XbimMatrix3D(v.X, v.Y, 0, 0, v.Y, v.X, 0, 0, 0, 0, 1, 0, axis2.Location.X, axis2.Location.Y, 0, 1);
     }
     else
         transform = new XbimMatrix3D(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, axis2.Location.X, axis2.Location.Y,
                             axis2.Location.Z, 1);
     if (maps != null) maps.TryAdd(axis2.EntityLabel, transform);
     return (XbimMatrix3D)transform;
 }
Example #15
0
 public static Task TransferContentAsync(ConcurrentDictionary<string, int> input, BlockingCollection<Info> output)
 {
   return Task.Run(() =>
     {
       foreach (var word in input.Keys)
       {
         int value;
         if (input.TryGetValue(word, out value))
         {
           var info = new Info { Word = word, Count = value };
           output.Add(info);
           ConsoleHelper.WriteLine(string.Format("stage 4: added {0}", info));
         }
       }
       output.CompleteAdding();
     });
 }
 public static Task TransferContentAsync(ConcurrentDictionary<string, int> input, BlockingCollection<Info> output)
 {
     return Task.Factory.StartNew(() =>
     {
         foreach (var word in input.Keys)
         {
             int value;
             if (input.TryGetValue(word, out value))
             {
                 var info = new Info { Word = word, Count = value };
                 output.Add(info);
                 ColoredConsole.WriteLine($"stage 4: added {info}");
             }
         }
         output.CompleteAdding();
     }, TaskCreationOptions.LongRunning);
 }
        internal static bool ContainsUsingAlias(this SyntaxTree tree, ConcurrentDictionary<SyntaxTree, bool> cache)
        {
            if (tree == null)
            {
                return false;
            }

            bool result;
            if (cache.TryGetValue(tree, out result))
            {
                return result;
            }

            bool generated = ContainsUsingAliasNoCache(tree);
            cache.TryAdd(tree, generated);
            return generated;
        }
        /// <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>&lt;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;
        }
		public IProperties GetProperties(ConcurrentDictionary<Type, int> seenTypes = null, int maxRecursion = 0)
		{
			var properties = new Properties();

			int seen;
			if (seenTypes != null && seenTypes.TryGetValue(_type, out seen) && seen > maxRecursion)
				return properties;

			foreach (var propertyInfo in _type.GetProperties())
			{
				var attribute = ElasticsearchPropertyAttribute.From(propertyInfo);
				if (attribute != null && attribute.Ignore)
					continue;
				var property = GetProperty(propertyInfo, attribute);
				properties.Add(propertyInfo, property);
			}

			return properties;
		}
Example #20
0
 /// <summary>
 /// Resolves the <see cref="SqlProjectionHandler">handlers</see> to which the message instance is assignable.
 /// </summary>
 /// <param name="handlers">The set of resolvable handlers.</param>
 /// <returns>A <see cref="SqlProjectionHandlerResolver">resolver</see>.</returns>
 public static SqlProjectionHandlerResolver WhenAssignableToHandlerMessageType(SqlProjectionHandler[] handlers)
 {
     if (handlers == null)
         throw new ArgumentNullException("handlers");
     var cache = new ConcurrentDictionary<Type, SqlProjectionHandler[]>();
     return message =>
     {
         if (message == null)
             throw new ArgumentNullException("message");
         SqlProjectionHandler[] result;
         if (!cache.TryGetValue(message.GetType(), out result))
         {
             result = cache.GetOrAdd(message.GetType(),
                 Array.FindAll(handlers,
                     handler => handler.Message.IsInstanceOfType(message)));
         }
         return result;
     };
 }
Example #21
0
        public override void Run()
        {
            ConcurrentDictionary<int, string> d = new ConcurrentDictionary<int, string>(CONCURRENCY_LEVEL, ARRAY_SIZE);

            for (int i = 0; i < 1000000; i++)
            {
                d.TryAdd(i, "abc");
            }

            string s = string.Empty;

            __sw.Reset();
            __sw.Start();

            Parallel.For(0, 1000000, i => d.TryGetValue(i, out s));

            __sw.Stop();

            Console.WriteLine("Parallel Get ConcurrentDictionary: {0}", __sw.ElapsedTicks);
        }
Example #22
0
            static TranslateCommands()
            {
                TranslatedChannels = new ConcurrentDictionary<ulong, bool>();
                UserLanguages = new ConcurrentDictionary<UserChannelPair, string>();

                NadekoBot.Client.MessageReceived += (msg) =>
                {
                    var umsg = msg as IUserMessage;
                    if(umsg == null)
                        return Task.CompletedTask;

                    bool autoDelete;
                    if (!TranslatedChannels.TryGetValue(umsg.Channel.Id, out autoDelete))
                        return Task.CompletedTask;

                    var t = Task.Run(async () =>
                    {
                        var key = new UserChannelPair()
                        {
                            UserId = umsg.Author.Id,
                            ChannelId = umsg.Channel.Id,
                        };

                        string langs;
                        if (!UserLanguages.TryGetValue(key, out langs))
                            return;

                        try
                        {
                            var text = await TranslateInternal(umsg, langs, umsg.Resolve(UserMentionHandling.Ignore), true)
                                                .ConfigureAwait(false);
                            if (autoDelete)
                                try { await umsg.DeleteAsync().ConfigureAwait(false); } catch { }
                            await umsg.Channel.SendMessageAsync($"{umsg.Author.Mention} `:` "+text.Replace("<@ ", "<@").Replace("<@! ", "<@!")).ConfigureAwait(false);
                        }
                        catch { }

                    });
                    return Task.CompletedTask;
                };
            }
Example #23
0
 private static void AddOrIncrementValue(string key, ConcurrentDictionary<string, int> dict)
 {
   bool success = false;
   while (!success)
   {
     int value;
     if (dict.TryGetValue(key, out value))
     {
       if (dict.TryUpdate(key, value + 1, value))
       {
         success = true;
       }
     }
     else
     {
       if (dict.TryAdd(key, 1))
       {
         success = true;
       }
     }
   }
 }
Example #24
0
        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 blockX = (index >> 12 & 0xf);
                int blockY = (index & 0xff);
                int blockZ = (index >> 8 & 0xf);
                byte blockId = (byte)GetType(blockX, blockY, blockZ);
                byte data = GetData(blockX, blockY, blockZ);

                World.Server.SendPacketToNearbyPlayers(World, Coords, new BlockChangePacket
                {X = Coords.WorldX + blockX, Y = (sbyte) blockY, Z = Coords.WorldZ + blockZ, 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 blockX = (index >> 12 & 0xf);
                    int blockY = (index & 0xff);
                    int blockZ = (index >> 8 & 0xf);

                    data[count] = (sbyte)GetData(blockX, blockY, blockZ);
                    types[count] = (sbyte)GetType(blockX, blockY, blockZ);
                    blocks[count] = index;
                    ++count;
                }
                World.Server.SendPacketToNearbyPlayers(World, Coords, new MultiBlockChangePacket { CoordsArray = blocks, Metadata = data, Types = types, ChunkCoords = Coords });
            }
            else
            {
                World.Server.SendPacketToNearbyPlayers(World, Coords, new MapChunkPacket { Chunk = this });
            }

            BlocksUpdating.Clear();
            base.UpdateBlocksToNearbyPlayers(state);
        }
        static void Main(string[] args) {

            // create the bank account instance
            BankAccount account = new BankAccount();

            // create a shared dictionary
            ConcurrentDictionary<object, int> sharedDict
                = new ConcurrentDictionary<object, int>();

            // create tasks to process the list
            Task<int>[] tasks = new Task<int>[10];
            for (int i = 0; i < tasks.Length; i++) {

                // put the initial value into the dictionary
                sharedDict.TryAdd(i, account.Balance);

                // create the new task
                tasks[i] = new Task<int>((keyObj) => {

                    // define variables for use in the loop
                    int currentValue;
                    bool gotValue;

                    // enter a loop for 1000 balance updates
                    for (int j = 0; j < 1000; j++) {
                        // get the current value from the dictionary
                        gotValue = sharedDict.TryGetValue(keyObj, out currentValue);
                        // increment the value and update the dictionary entry
                        sharedDict.TryUpdate(keyObj, currentValue + 1, currentValue);
                    }

                    // define the final result
                    int result;
                    // get our result from the dictionary
                    gotValue = sharedDict.TryGetValue(keyObj, out result);
                    // return the result value if we got one
                    if (gotValue) {
                        return result;
                    } else {
                        // there was no result available - we have encountered a problem
                        throw new Exception(
                            String.Format("No data item available for key {0}", keyObj));
                    }
                }, i);

                // start the new task
                tasks[i].Start();
            }

            // update the balance of the account using the task results
            for (int i = 0; i < tasks.Length; i++) {
                account.Balance += tasks[i].Result;
            }

            // write out the counter value
            Console.WriteLine("Expected value {0}, Balance: {1}",
                10000, account.Balance);

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();

        }
Example #26
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="textureCache">TextureCache</param>
 /// <param name="size">size</param>
 /// <param name="key">key, which was used to load the Texture into the cache</param>
 public Tile(ConcurrentDictionary<string, Texture2D> textureCache, int size, string key)
 {
     Texture2D texture;
     textureCache.TryGetValue(key, out texture);
     xSize = ySize = size;
     if (texture.Bounds.Height == ySize && texture.Bounds.Width == xSize)
     {
         this.texture = texture;
     }
     else
     {
         throw new Exception("Wrong texturesize!");
     }
 }
Example #27
0
        /// <summary>
        /// Loads the specified type if it exists in the given assembly. If the type name is fully qualified, then a match (if
        /// any) is unambiguous; otherwise, if there are multiple types with the same name in different namespaces, the first type
        /// found will be returned.
        /// </summary>
        private LoadedType GetLoadedType(object cacheLock, object loadInfoToTypeLock, ConcurrentDictionary<TypeFilter, ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes>> cache, string typeName, AssemblyLoadInfo assembly)
        {
            // A given typefilter have been used on a number of assemblies, Based on the typefilter we will get another dictionary which 
            // will map a specific AssemblyLoadInfo to a AssemblyInfoToLoadedTypes class which knows how to find a typeName in a given assembly.
            ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes> loadInfoToType = null;
            lock (cacheLock)
            {
                if (!cache.TryGetValue(_isDesiredType, out loadInfoToType))
                {
                    loadInfoToType = new ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes>();
                    cache.TryAdd(_isDesiredType, loadInfoToType);
                }
            }

            // Get an object which is able to take a typename and determine if it is in the assembly pointed to by the AssemblyInfo.
            AssemblyInfoToLoadedTypes typeNameToType = null;
            lock (loadInfoToTypeLock)
            {
                if (!loadInfoToType.TryGetValue(assembly, out typeNameToType))
                {
                    typeNameToType = new AssemblyInfoToLoadedTypes(_isDesiredType, assembly);
                    loadInfoToType.TryAdd(assembly, typeNameToType);
                }
            }

            return typeNameToType.GetLoadedTypeByTypeName(typeName);
        }
 private static CounterStatistic FindCounter(ConcurrentDictionary<string, CounterStatistic> counters, StatisticName name, CounterStorage storage)
 {
     CounterStatistic stat;
     if (counters.TryGetValue(name.Name, out stat))
     {
         return stat;
     }
     stat = CounterStatistic.FindOrCreate(name, storage);
     counters.TryAdd(name.Name, stat);
     return stat;
 }
        /// <summary>
        /// Parallelized version of CalculateCentroid().
        /// </summary>
        public CoordinateVector CalculateCentroidParallel(IList<CoordinateVector> coordList)
        {
            // Special case - one item in list, it *is* the centroid.
            if (1 == coordList.Count)
            {
                return coordList[0];
            }

            // Each coordinate element has an ID. Here we calculate the total for each ID across all CoordinateVectors,
            // then divide the totals by the number of CoordinateVectors to get the average for each ID. That is, we 
            // calculate the component-wise mean.

            // ConcurrentDictionary provides a low-locking strategy that greatly improves performance here 
            // compared to using mutual exclusion locks or even ReadWriterLock(s).
            ConcurrentDictionary<ulong,double[]> coordElemTotals = new ConcurrentDictionary<ulong, double[]>();

            // Loop over coords.
            Parallel.ForEach(coordList, delegate(CoordinateVector coord)
            {
                // Loop over each element within the current coord.
                foreach (KeyValuePair<ulong, double> coordElem in coord.CoordArray)
                {
                    // If the ID has previously been encountered then add the current element value to it, otherwise
                    // add a new double[1] to hold the value. 
                    // Note that we wrap the double value in an object so that we do not have to re-insert values
                    // to increment them. In tests this approach was about 40% faster (including GC overhead).

                    // If position is zero then (A) skip doing any work, and (B) zero will break the following logic.
                    if (coordElem.Value == 0.0) {
                        continue;
                    }

                    double[] doubleWrapper;
                    if (coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper))
                    {   // By locking just the specific object that holds the value we are incrementing
                        // we greatly reduce the amount of lock contention.
                        lock(doubleWrapper)
                        {
                            doubleWrapper[0] += coordElem.Value;
                        }
                    }
                    else
                    {
                        doubleWrapper = new double[] { coordElem.Value };
                        if (!coordElemTotals.TryAdd(coordElem.Key, doubleWrapper))
                        {
                            if(coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper))
                            {
                                lock (doubleWrapper)
                                {
                                    doubleWrapper[0] += coordElem.Value;
                                }
                            }
                        }
                    }
                }
            });

            // Put the unique coord elems from coordElemTotals into a list, dividing each element's value
            // by the total number of coords as we go.
            double coordCountReciprocol = 1.0 / (double)coordList.Count;
            KeyValuePair<ulong, double>[] centroidElemArr = new KeyValuePair<ulong, double>[coordElemTotals.Count];
            int i = 0;
            foreach (KeyValuePair<ulong, double[]> coordElem in coordElemTotals)
            {   // For speed we multiply by reciprocol instead of dividing by coordCount.
                centroidElemArr[i++] = new KeyValuePair<ulong, double>(coordElem.Key, coordElem.Value[0] * coordCountReciprocol);
            }

            // Coord elements within a CoordinateVector must be sorted by ID.
            Array.Sort(centroidElemArr, delegate(KeyValuePair<ulong, double> x, KeyValuePair<ulong, double> y)
            {
                if (x.Key < y.Key) {
                    return -1;
                }
                if (x.Key > y.Key) {
                    return 1;
                }
                return 0;
            });

            // Use the new list of elements to construct a centroid CoordinateVector.
            return new CoordinateVector(centroidElemArr);
        }
 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;
 }