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


C# ConcurrentDictionary类代码示例

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


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

示例1: SpeechService

        public SpeechService()
        {
            this.textToSpeech = new TextToSpeech(Application.Context, this);
            this.textToSpeech.SetOnUtteranceProgressListener(this);

            this.inFlightSpeech = new ConcurrentDictionary<int, AsyncSubject<Unit>>();
        }
开发者ID:gregjones60,项目名称:WorkoutWotch,代码行数:7,代码来源:SpeechService.cs

示例2: BuildSerializer

        public override ValueSerializer BuildSerializer(Serializer serializer, Type type,
            ConcurrentDictionary<Type, ValueSerializer> typeMapping)
        {
            var x = new ObjectSerializer(type);
            typeMapping.TryAdd(type, x);

            var elementType = GetEnumerableType(type);
            var arrType = elementType.MakeArrayType();
            var listModule = type.Assembly.GetType("Microsoft.FSharp.Collections.ListModule");
            var ofArray = listModule.GetMethod("OfArray");
            var ofArrayConcrete = ofArray.MakeGenericMethod(elementType);
            var ofArrayCompiled = CodeGenerator.CompileToDelegate(ofArrayConcrete, arrType);
            var toArray = listModule.GetMethod("ToArray");
            var toArrayConcrete = toArray.MakeGenericMethod(elementType);
            var toArrayCompiled = CodeGenerator.CompileToDelegate(toArrayConcrete, type);

            ValueWriter writer = (stream, o, session) =>
            {
                var arr = toArrayCompiled(o);
                var arrSerializer = serializer.GetSerializerByType(arrType);
                arrSerializer.WriteValue(stream,arr,session);
            };

            ValueReader reader = (stream, session) =>
            {               
                var arrSerializer = serializer.GetSerializerByType(arrType);
                var items = (Array)arrSerializer.ReadValue(stream, session);                          
                var res = ofArrayCompiled(items);
                return res;
            };
            x.Initialize(reader, writer);
            return x;
        }
开发者ID:philiplaureano,项目名称:Wire,代码行数:33,代码来源:FSharpListSerializerFactory.cs

示例3: GetAmicableNumbersParallelized

        public static ConcurrentDictionary<int, int> GetAmicableNumbersParallelized(int n)
        {
            ConcurrentDictionary<int, int> amicableNumbers =
                new ConcurrentDictionary<int, int>();

            Parallel.For(1, n, (i) =>
            {
                Parallel.For(i, n, (j) =>
                {
                    if (i != j &&
                        i == GetEvenDivisors(j).Sum() &&
                        j == GetEvenDivisors(i).Sum())
                    {
                        amicableNumbers.TryAdd(i, j);
                        Console.WriteLine("Found {0} and {1} using Thread {2}.",
                            GetEvenDivisors(i).Sum(),
                            GetEvenDivisors(j).Sum(),
                            Thread.CurrentThread.ManagedThreadId);
                    }
                }
                );
            });

            return amicableNumbers;
        }
开发者ID:re-src,项目名称:ParallelComputingDemo,代码行数:25,代码来源:Computation.cs

示例4: test3

 static void test3()
 {
     ConcurrentDictionary<string, string> list = new ConcurrentDictionary<string, string>();
     list["a"]="a";
     list["b"] = "b";
     Console.WriteLine(list.Count);
 }
开发者ID:Yuanxiangz,项目名称:WorkSpace,代码行数:7,代码来源:Program.cs

示例5: 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);
            }
        }
开发者ID:kenwilcox,项目名称:ConcurrentCollections,代码行数:31,代码来源:Program2.cs

示例6: FileSystemRefreshableWatcher

 public FileSystemRefreshableWatcher(IFileSystemWatcher watcher) : base(watcher)
 {
     _refreshTokenSource = new CancellationTokenSource();
     _waitingThreadsEvents = new ConcurrentDictionary<Thread, ManualResetEventSlim>();
     IsRefreshing = false;
     _refreshLock = new object();
 }
开发者ID:DeadlyEmbrace,项目名称:FileSystemWatcherAlts,代码行数:7,代码来源:FileSystemRefreshableWatcher.cs

示例7: LightningEnvironment

        public LightningEnvironment(string directory, EnvironmentOpenFlags openFlags)
        {
            if (String.IsNullOrWhiteSpace(directory))
                throw new ArgumentException("Invalid directory name");

            IntPtr handle = default(IntPtr);
            Native.Execute(() => Native.mdb_env_create(out handle));

            _shouldDispose = true;
            
            _handle = handle;

            this.Directory = directory;
            _openFlags = openFlags;

            _mapSize = DefaultMapSize;
            _maxDbs = DefaultMaxDatabases;

            _openedDatabases = new ConcurrentDictionary<string, LightningDatabase>();
            _databasesForReuse = new HashSet<uint>();

            ConverterStore = new ConverterStore();
            var defaultConverters = new DefaultConverters();
            defaultConverters.RegisterDefault(this);
        }
开发者ID:pilgrimzh,项目名称:Lightning.NET,代码行数:25,代码来源:LightningEnvironment.cs

示例8: ClusterMembership

 public ClusterMembership(ClusterMembershipConfiguration config,  ILogger logger)
 {
     lastPingTime = DateTime.UtcNow;
     this.config = config;
     this.logger = logger;
     clusterMembers = new ConcurrentDictionary<SocketEndpoint, ClusterMemberMeta>();
 }
开发者ID:gitter-badger,项目名称:kino,代码行数:7,代码来源:ClusterMembership.cs

示例9: QueryCacheManager

 /// <summary>Static constructor.</summary>
 static QueryCacheManager()
 {
     Cache = new MemoryCache(new MemoryCacheOptions());
     DefaultMemoryCacheEntryOptions = new MemoryCacheEntryOptions();
     CachePrefix = "Z.EntityFramework.Plus.QueryCacheManager;";
     CacheTags = new ConcurrentDictionary<string, List<string>>();
 }
开发者ID:DebugOfTheRoad,项目名称:EntityFramework-Plus,代码行数:8,代码来源:QueryCacheManager.cs

示例10: SocketEventClient

 public SocketEventClient(string id, string url)
 {
     this.ClientId = id;
     this.Url = url;
     this.eventStore = new ConcurrentDictionary<string, dynamic>();
     this.locker = new Semaphore(1, 1);
 }
开发者ID:hwj383,项目名称:SocketEvent.NET,代码行数:7,代码来源:SocketEventClient.cs

示例11: 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

示例12: GetMetrics

        public IEnumerable<JobMetric> GetMetrics(IDictionary<Guid, IDictionary<Guid, int?>> packagesWithJobsAndLastBuildNumber)
        {
            using (var gateway = PackageConfigurationGatewayFactory())
            {
                var result = new ConcurrentDictionary<string, JobMetric>();
                foreach (var packagesWithJob in packagesWithJobsAndLastBuildNumber)
                {
                    var configuration = gateway.GetPackageConfiguration(packagesWithJob.Key);
                    if (configuration == null || string.IsNullOrEmpty(configuration.JenkinsServerUrl))
                        continue;
                    var jobs = gateway.GetJobs(packagesWithJob.Value.Keys)
                        .Join(packagesWithJob.Value, j => j.ExternalId, k => k.Key,
                            (j, k) => new {Job = j, BuildNumber = k.Value});

                    JenkinsRequest.ChangeBaseUrl(configuration.JenkinsServerUrl);
                    JenkinsRequest.ChangeBaseUrl(configuration.JenkinsServerUrl);
                    Parallel.ForEach(jobs, j =>
                    {
                        var metrics = JenkinsRequest.GetJobMetrics(j.Job.Name, j.BuildNumber, configuration.TimeZone);
                        if (metrics == null) return;

                        if (!result.TryAdd(j.Job.Name, metrics))
                        {
                            Logger.ErrorFormat("Jenkins Job measurements not stored. Job={0}, Id={1}",
                                j.Job.Name, j.Job.ExternalId);
                        }
                    });
                }
                return result.Values.ToArray();
            }
        }
开发者ID:justinconnell,项目名称:remi,代码行数:31,代码来源:JenkinsDeploymentTool.cs

示例13: MainMethod

        public void MainMethod()
        {
            Console.WriteLine("Concurrent Dictionary Run implementation");
            ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();
            if(dictionary.TryAdd("k1",10))
            {
                Console.WriteLine("Added Key k1");
            }

            if(dictionary.TryUpdate("k1",19,10))
            {
                Console.WriteLine("Updated Key k1");
            }

            if (dictionary.TryUpdate("k1", 19, 10))
            {
                Console.WriteLine("Updated Key k1");
            }
            else
                Console.WriteLine("Failed to Update");

            dictionary["k1"] = 16;

            int r1 = dictionary.AddOrUpdate("k1", 2, (s, i) => i * 2);
            Console.WriteLine(r1);
            int r3 = dictionary.AddOrUpdate("k3", 2, (s, i) => i * 2);
            Console.WriteLine(r3);
            int r2 = dictionary.GetOrAdd("k2", 4);
            Console.WriteLine(r2);
        }
开发者ID:mayankaggarwal,项目名称:MyConcepts,代码行数:30,代码来源:Concept18.cs

示例14: WorkContext

	    public WorkContext()
	    {
	        DoNotTouchAgainIfMissingReferences = new ConcurrentDictionary<int, ConcurrentSet<string>>();
            CurrentlyRunningQueries = new ConcurrentDictionary<string, ConcurrentSet<ExecutingQueryInfo>>(StringComparer.OrdinalIgnoreCase);
            MetricsCounters = new MetricsCountersManager();
	        InstallGauges();
	    }
开发者ID:ReginaBricker,项目名称:ravendb,代码行数:7,代码来源:WorkContext.cs

示例15: Consumer

        public Consumer(string groupName, ConsumerSetting setting)
        {
            if (groupName == null)
            {
                throw new ArgumentNullException("groupName");
            }
            GroupName = groupName;
            Setting = setting ?? new ConsumerSetting();

            _lockObject = new object();
            _subscriptionTopics = new Dictionary<string, HashSet<string>>();
            _topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>();
            _pullRequestDict = new ConcurrentDictionary<string, PullRequest>();
            _remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.SocketSetting, Setting.LocalAddress);
            _adminRemotingClient = new SocketRemotingClient(Setting.BrokerAdminAddress, Setting.SocketSetting, Setting.LocalAdminAddress);
            _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
            _scheduleService = ObjectContainer.Resolve<IScheduleService>();
            _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);

            _remotingClient.RegisterConnectionEventListener(new ConnectionEventListener(this));

            if (Setting.MessageHandleMode == MessageHandleMode.Sequential)
            {
                _consumingMessageQueue = new BlockingCollection<ConsumingMessage>();
                _consumeMessageWorker = new Worker("ConsumeMessage", () => HandleMessage(_consumingMessageQueue.Take()));
            }
            _messageRetryQueue = new BlockingCollection<ConsumingMessage>();
        }
开发者ID:uliian,项目名称:equeue,代码行数:29,代码来源:Consumer.cs


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