• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ConcurrentDictionary类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: FooDb

        static FooDb()
        {
            var data = Enumerable.Range(1, 10)
                                 .Select(i => new Foo { Id = i, Name = string.Format("Foo {0}", i) });

            foos = new ConcurrentDictionary<int, Foo>(data.ToDictionary(f => f.Id, f => f));
        }
开发者ID:yonglehou,项目名称:ServiceProxy,代码行数:7,代码来源:FooService.cs


示例17: ShouldBeAbleToPullExistingInfoFromCache

            public void ShouldBeAbleToPullExistingInfoFromCache()
            {
                var monitorConfig = new MonitorConfig { Name = "Test" };
                var reduceLevels = new List<ReduceLevel>();

                var connection = new Mock<IDbConnection>();
                var connectionInstance = connection.Object;

                var storageCommands = new Mock<IStorageCommands>();
                storageCommands.Setup(x => x.CreateConfigAndReduceLevels(monitorConfig, reduceLevels, connectionInstance));

                var setupSystemTables = new Mock<ISetupSystemTables>();
                setupSystemTables.Setup(x => x.ValidateAndCreateDataTables(connectionInstance)).Verifiable();

                var monitorConfigsDictionary = new ConcurrentDictionary<string, MonitorConfig>();

                var cache = new Mock<IDataCache>();
                cache.SetupGet(x => x.MonitorConfigs).Returns(monitorConfigsDictionary).Verifiable();

                var storageFactory = new Mock<IStorageFactory>();
                storageFactory.Setup(x => x.CreateConnection()).Returns(connectionInstance).Verifiable();

                var settings = BuildSettings();

                var defaults = new SetupMonitorConfig(storageCommands.Object, setupSystemTables.Object, cache.Object, storageFactory.Object, settings.Object);
                defaults.CreateDefaultReduceLevels(monitorConfig, reduceLevels);

                Assert.Equal(1, monitorConfigsDictionary.Count);
                Assert.True(monitorConfigsDictionary.ContainsKey("Test"));

                storageCommands.VerifyAll();
                setupSystemTables.VerifyAll();
                storageFactory.VerifyAll();
                cache.VerifyAll();
            }
开发者ID:Zocdoc,项目名称:ZocMon,代码行数:35,代码来源:TestForSetupMonitorConfig.cs


示例18: ServerConfig

 public ServerConfig(IEnumerable<Tuple<WikiConfig, IPageCache>> config)
 {
     configMap = new ConcurrentDictionary<string, Tuple<WikiConfig, MasterRepository, IPageCache>>(
         config.ToDictionary(
             c => CreateSafeName(c.Item1.SiteName),
             c => new Tuple<WikiConfig, MasterRepository, IPageCache>(c.Item1, new MasterRepository(c.Item1.Convertor.FileExtension), c.Item2)));
 }
开发者ID:sbyse,项目名称:icklewik,代码行数:7,代码来源:ServerConfig.cs


示例19: OrleansTaskScheduler

        private OrleansTaskScheduler(int maxActiveThreads, TimeSpan delayWarningThreshold, TimeSpan activationSchedulingQuantum,
            TimeSpan turnWarningLengthThreshold, bool injectMoreWorkerThreads, LimitValue maxPendingItemsLimit)
        {
            Instance = this;
            DelayWarningThreshold = delayWarningThreshold;
            WorkItemGroup.ActivationSchedulingQuantum = activationSchedulingQuantum;
            TurnWarningLengthThreshold = turnWarningLengthThreshold;
            applicationTurnsStopped = false;
            MaxPendingItemsLimit = maxPendingItemsLimit;
            workgroupDirectory = new ConcurrentDictionary<ISchedulingContext, WorkItemGroup>();
            RunQueue = new WorkQueue();
            logger.Info("Starting OrleansTaskScheduler with {0} Max Active application Threads and 1 system thread.", maxActiveThreads);
            Pool = new WorkerPool(this, maxActiveThreads, injectMoreWorkerThreads);
            IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount);
            IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_INSTANTANEOUS_PER_QUEUE, "Scheduler.LevelOne"), () => RunQueueLength);

            if (!StatisticsCollector.CollectShedulerQueuesStats) return;

            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo);
        }
开发者ID:naeemkhedarun,项目名称:orleans,代码行数:25,代码来源:OrleansTaskScheduler.cs


示例20: CouchbaseLiteHttpClientFactory

        public CouchbaseLiteHttpClientFactory(CookieStore cookieStore)
        {
            this.cookieStore = cookieStore;
            Headers = new ConcurrentDictionary<string,string>();

            // Disable SSL 3 fallback to mitigate POODLE vulnerability.
            ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;

            //
            // Source: http://msdn.microsoft.com/en-us/library/office/dd633677(v=exchg.80).aspx
            // ServerCertificateValidationCallback returns true if either of the following criteria are met:
            // The certificate is valid and signed with a valid root certificate.
            // The certificate is self-signed by the server that returned the certificate.
            //
            ServicePointManager.ServerCertificateValidationCallback = 
            (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
            {
                // If the certificate is a valid, signed certificate, return true.
                if (sslPolicyErrors == SslPolicyErrors.None)
                {
                    return true;
                }

                // If there are errors in the certificate chain, look at each error to determine the cause.
                if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
                {
                    if (chain != null && chain.ChainStatus != null)
                    {
                        foreach (X509ChainStatus status in chain.ChainStatus)
                        {
                            if ((certificate.Subject == certificate.Issuer) &&
                                (status.Status == X509ChainStatusFlags.UntrustedRoot))
                            {
                                // Self-signed certificates with an untrusted root are valid. 
                                continue;
                            }
                            else
                            {
                                if (status.Status != X509ChainStatusFlags.NoError)
                                {
                                    // If there are any other errors in the certificate chain, the certificate is invalid,
                                    // so the method returns false.
                                    return false;
                                }
                            }
                        }
                    }

                    // When processing reaches this line, the only errors in the certificate chain are 
                    // untrusted root errors for self-signed certificates. These certificates are valid
                    // for default Exchange server installations, so return true.
                    return true;
                }
                else
                {
                    // In all other cases, return false.
                    return false;
                }
            };
        }
开发者ID:ertrupti9,项目名称:couchbase-lite-net,代码行数:60,代码来源:CouchbaseLiteHttpClientFactory.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ConcreteAST.Segment类代码示例发布时间:2022-05-27
下一篇:
C# AzureVMConfigInfo类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap