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


C# ConcurrentSet.TryAdd方法代码示例

本文整理汇总了C#中ConcurrentSet.TryAdd方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentSet.TryAdd方法的具体用法?C# ConcurrentSet.TryAdd怎么用?C# ConcurrentSet.TryAdd使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ConcurrentSet的用法示例。


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

示例1: GetPrefetcherFor

		private PrefetchingBehavior GetPrefetcherFor(Etag fromEtag, ConcurrentSet<PrefetchingBehavior> usedPrefetchers)
		{
			foreach (var prefetchingBehavior in prefetchingBehaviors)
			{
				if (prefetchingBehavior.CanUsePrefetcherToLoadFrom(fromEtag) && usedPrefetchers.TryAdd(prefetchingBehavior))
					return prefetchingBehavior;
			}

			var newPrefetcher = Database.Prefetcher.CreatePrefetchingBehavior(PrefetchingUser.SqlReplicator, null, "SqlReplication");

			prefetchingBehaviors.Add(newPrefetcher);
			usedPrefetchers.Add(newPrefetcher);

			return newPrefetcher;
		}
开发者ID:GorelH,项目名称:ravendb,代码行数:15,代码来源:SqlReplicationTask.cs

示例2: IndexDocuments

		public override IndexingPerformanceStats IndexDocuments(AbstractViewGenerator viewGenerator, IndexingBatch batch, IStorageActionsAccessor actions, DateTime minimumTimestamp, CancellationToken token)
		{
			token.ThrowIfCancellationRequested();

			var count = 0;
			var sourceCount = 0;
			var deleted = new Dictionary<ReduceKeyAndBucket, int>();
			var performance = RecordCurrentBatch("Current Map", "Map", batch.Docs.Count);
			var performanceStats = new List<BasePerformanceStats>();

			var usedStorageAccessors = new ConcurrentSet<IStorageActionsAccessor>();

			if (usedStorageAccessors.TryAdd(actions))
			{
				var storageCommitDuration = new Stopwatch();

				actions.BeforeStorageCommit += storageCommitDuration.Start;

				actions.AfterStorageCommit += () =>
				{
					storageCommitDuration.Stop();

					performanceStats.Add(PerformanceStats.From(IndexingOperation.StorageCommit, storageCommitDuration.ElapsedMilliseconds));
				};
			}

			var deleteMappedResultsDuration = new Stopwatch();
			var documentsWrapped = batch.Docs.Select(doc =>
			{
				token.ThrowIfCancellationRequested();

				sourceCount++;
				var documentId = doc.__document_id;

				using (StopwatchScope.For(deleteMappedResultsDuration))
				{
					actions.MapReduce.DeleteMappedResultsForDocumentId((string)documentId, indexId, deleted);
				}
				
				return doc;
			})
			.Where(x => x is FilteredDocument == false)
			.ToList();

			performanceStats.Add(new PerformanceStats
			{
				Name = IndexingOperation.Map_DeleteMappedResults,
				DurationMs = deleteMappedResultsDuration.ElapsedMilliseconds,
			});

			var allReferencedDocs = new ConcurrentQueue<IDictionary<string, HashSet<string>>>();
			var allReferenceEtags = new ConcurrentQueue<IDictionary<string, Etag>>();
			var allState = new ConcurrentQueue<Tuple<HashSet<ReduceKeyAndBucket>, IndexingWorkStats, Dictionary<string, int>>>();

			var parallelOperations = new ConcurrentQueue<ParallelBatchStats>();

			var parallelProcessingStart = SystemTime.UtcNow;

			BackgroundTaskExecuter.Instance.ExecuteAllBuffered(context, documentsWrapped, partition =>
			{
                token.ThrowIfCancellationRequested();
				var parallelStats = new ParallelBatchStats
				{
					StartDelay = (long)(SystemTime.UtcNow - parallelProcessingStart).TotalMilliseconds
				};

				var localStats = new IndexingWorkStats();
				var localChanges = new HashSet<ReduceKeyAndBucket>();
				var statsPerKey = new Dictionary<string, int>();

				var linqExecutionDuration = new Stopwatch();
				var reduceInMapLinqExecutionDuration = new Stopwatch();
				var putMappedResultsDuration = new Stopwatch();
				var convertToRavenJObjectDuration = new Stopwatch();

				allState.Enqueue(Tuple.Create(localChanges, localStats, statsPerKey));

				using (CurrentIndexingScope.Current = new CurrentIndexingScope(context.Database, PublicName))
				{
					// we are writing to the transactional store from multiple threads here, and in a streaming fashion
					// should result in less memory and better perf
					context.TransactionalStorage.Batch(accessor =>
					{
						if (usedStorageAccessors.TryAdd(accessor))
						{
							var storageCommitDuration = new Stopwatch();

							accessor.BeforeStorageCommit += storageCommitDuration.Start;

							accessor.AfterStorageCommit += () =>
							{
								storageCommitDuration.Stop();

								parallelStats.Operations.Add(PerformanceStats.From(IndexingOperation.StorageCommit, storageCommitDuration.ElapsedMilliseconds));
							};
						}

						var mapResults = RobustEnumerationIndex(partition, viewGenerator.MapDefinitions, localStats, linqExecutionDuration);
						var currentDocumentResults = new List<object>();
						string currentKey = null;
//.........这里部分代码省略.........
开发者ID:felipeleusin,项目名称:ravendb,代码行数:101,代码来源:MapReduceIndex.cs

示例3: TryGetDefaultPrefetcher

        private PrefetchingBehavior TryGetDefaultPrefetcher(Etag fromEtag, ConcurrentSet<PrefetchingBehavior> usedPrefetchers)
        {
            if (defaultPrefetchingBehavior.CanUseDefaultPrefetcher(fromEtag) &&
                usedPrefetchers.TryAdd(defaultPrefetchingBehavior))
            {
                return defaultPrefetchingBehavior;
            }

            return null;
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:10,代码来源:IndexingExecuter.cs

示例4: GetPrefetcherFor

        private PrefetchingBehavior GetPrefetcherFor(Etag fromEtag, ConcurrentSet<PrefetchingBehavior> usedPrefetchers)
        {
            foreach (var prefetchingBehavior in prefetchingBehaviors)
            {
                // at this point we've already verified that we can't use the default prefetcher
                // if it's empty, we don't need to use it
                if (prefetchingBehavior.IsDefault == false && prefetchingBehavior.IsEmpty() && usedPrefetchers.TryAdd(prefetchingBehavior))
                    return prefetchingBehavior;
            }

            var newPrefetcher = prefetcher.CreatePrefetchingBehavior(PrefetchingUser.Indexer, autoTuner, string.Format("Etags from: {0}", fromEtag));

            prefetchingBehaviors.Add(newPrefetcher);
            usedPrefetchers.Add(newPrefetcher);

            return newPrefetcher;
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:17,代码来源:IndexingExecuter.cs

示例5: TryGetPrefetcherFor

        private PrefetchingBehavior TryGetPrefetcherFor(Etag fromEtag, ConcurrentSet<PrefetchingBehavior> usedPrefetchers)
        {
            foreach (var prefetchingBehavior in prefetchingBehaviors)
            {
                if (prefetchingBehavior.CanUsePrefetcherToLoadFromUsingExistingData(fromEtag) &&
                    usedPrefetchers.TryAdd(prefetchingBehavior))
                {
                    return prefetchingBehavior;
                }
            }

            return null;
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:13,代码来源:IndexingExecuter.cs

示例6: GetPrefetcherFor

		private PrefetchingBehavior GetPrefetcherFor(Etag fromEtag, ConcurrentSet<PrefetchingBehavior> usedPrefetchers)
		{
			foreach (var prefetchingBehavior in prefetchingBehaviors)
			{
				if (prefetchingBehavior.CanUsePrefetcherToLoadFrom(fromEtag) && usedPrefetchers.TryAdd(prefetchingBehavior))
					return prefetchingBehavior;
			}

			var newPrefetcher = prefetcher.CreatePrefetchingBehavior(PrefetchingUser.Indexer, autoTuner,string.Format("Etags from: {0}", fromEtag));

			var recentEtag = Etag.Empty;
			context.Database.TransactionalStorage.Batch(accessor =>
			{
				recentEtag = accessor.Staleness.GetMostRecentDocumentEtag();
			});

			if (recentEtag.Restarts != fromEtag.Restarts || Math.Abs(recentEtag.Changes - fromEtag.Changes) > context.CurrentNumberOfItemsToIndexInSingleBatch)
			{
				// If the distance between etag of a recent document in db and etag to index from is greater than NumberOfItemsToProcessInSingleBatch
				// then prevent the prefetcher from loading newly added documents. For such prefetcher we will relay only on future batches to prefetch docs to avoid
				// large memory consumption by in-memory prefetching queue that would hold all the new documents, but it would be a long time before we can reach them.
				newPrefetcher.DisableCollectingDocumentsAfterCommit = true;
			}

			prefetchingBehaviors.Add(newPrefetcher);
			usedPrefetchers.Add(newPrefetcher);

			return newPrefetcher;
		}
开发者ID:VPashkov,项目名称:ravendb,代码行数:29,代码来源:IndexingExecuter.cs

示例7: GetPrefetcherFor

		private PrefetchingBehavior GetPrefetcherFor(Etag fromEtag, ConcurrentSet<PrefetchingBehavior> usedPrefetchers)
		{
			foreach (var prefetchingBehavior in prefetchingBehaviors)
			{
				if (prefetchingBehavior.CanUsePrefetcherToLoadFrom(fromEtag) && usedPrefetchers.TryAdd(prefetchingBehavior))
					return prefetchingBehavior;
			}

			var newPrefetcher = prefetcher.CreatePrefetchingBehavior(PrefetchingUser.Indexer, autoTuner);
			
			prefetchingBehaviors.Add(newPrefetcher);
			usedPrefetchers.Add(newPrefetcher);

			return newPrefetcher;
		}
开发者ID:cocytus,项目名称:ravendb,代码行数:15,代码来源:IndexingExecuter.cs

示例8: CreateAsync

      public async Task<IRyuContainer> CreateAsync(IReadOnlySet<ITransportFactory> transportFactories, Guid? forceId = null) {
         var container = root.CreateChildContainer();
         var proxyGenerator = container.GetOrDefault<ProxyGenerator>() ?? new ProxyGenerator();
         var shutdownCancellationTokenSource = new CancellationTokenSource();

         // Auditing Subsystem
         var auditService = new AuditService(shutdownCancellationTokenSource.Token);
         auditService.Initialize();

         // management tier containers
         var mobContextContainer = new MobContextContainer();
         var mobContextFactory = new MobContextFactory(auditService);
         var mobOperations = new MobOperations(mobContextFactory, mobContextContainer);

         // Other Courier Stuff
         var identity = Identity.Create(forceId);
         var routingTable = new RoutingTable();
         var peerDiscoveryEventBus = new AsyncBus<PeerDiscoveryEvent>();
         var peerTable = new PeerTable(container, (table, peerId) => new PeerContext(table, peerId, peerDiscoveryEventBus));

         var inboundMessageRouter = new InboundMessageRouter();
         var inboundMessageDispatcher = new InboundMessageDispatcher(identity, peerTable, inboundMessageRouter);

         var transports = new ConcurrentSet<ITransport>();
         foreach (var transportFactory in transportFactories) {
            var transport = await transportFactory.CreateAsync(mobOperations, identity, routingTable, peerTable, inboundMessageDispatcher, auditService).ConfigureAwait(false);
            transports.TryAdd(transport);
         }

         var messenger = new Messenger(identity, transports, routingTable);

         container.Set(identity);
         container.Set(routingTable);
         container.Set(peerTable);
         container.Set(inboundMessageRouter);
         container.Set(messenger);

         //----------------------------------------------------------------------------------------
         // Service Tier - Service Discovery, Remote Method Invocation
         //----------------------------------------------------------------------------------------
         var localServiceRegistry = new LocalServiceRegistry(identity, messenger);
         var remoteServiceInvoker = new RemoteServiceInvoker(identity, messenger);
         var remoteServiceProxyContainer = new RemoteServiceProxyContainer(proxyGenerator, remoteServiceInvoker);
         inboundMessageRouter.RegisterHandler<RmiRequestDto>(localServiceRegistry.HandleInvocationRequestAsync);
         inboundMessageRouter.RegisterHandler<RmiResponseDto>(remoteServiceInvoker.HandleInvocationResponse);
         container.Set(localServiceRegistry);
         container.Set(remoteServiceProxyContainer);

         //----------------------------------------------------------------------------------------
         // Management Tier - DMI - Services
         //----------------------------------------------------------------------------------------
         var managementObjectService = new ManagementObjectService(mobContextContainer, mobOperations);
         localServiceRegistry.RegisterService<IManagementObjectService>(managementObjectService);
         container.Set(mobOperations);
         container.Set(managementObjectService);

         var facade = new CourierFacade(transports, container);
         container.Set(facade);

         return container;
      }
开发者ID:the-dargon-project,项目名称:courier,代码行数:61,代码来源:CourierContainerFactory.cs

示例9: MainWindow

      public MainWindow() {
         InitializeComponent();

         var pushedKeys = new ConcurrentSet<SWF.Keys>();

         var betterRunAutocompletionSource = new BetterRunAutocompletionSource();
         var webAutocompletionSource = new WebAutocompletionSource();
         webAutocompletionSource.Initialize();

         var githubAutocompletionSource = new GithubAutocompletionSource();

         var startMenuAutocompletionSource = new StartMenuAutocompletionSource();
         startMenuAutocompletionSource.Initialize();

         var bashAutocompletionSource = new BashAutocompletionSource();
         bashAutocompletionSource.Initialize();

         var viewModel = new RootViewModel(this, pushedKeys);
         viewModel.PropertyChanged += (s, e) => {
            try {
               var query = viewModel.Query;
               var autocompletionSources = new AutocompletionSource[] {
                  startMenuAutocompletionSource,
                  webAutocompletionSource,
                  githubAutocompletionSource,
                  bashAutocompletionSource,
                  betterRunAutocompletionSource
               };
               if (query.IndexOf(':') != -1 && query.IndexOf(':') <= 3) {
                  Console.WriteLine("[email protected]#@!#" + query);
                  var bobkuh = query.Substring(0, query.IndexOf(":"));
                  query = query.Substring(bobkuh.Length + 1);
                  autocompletionSources = autocompletionSources.Where(x => x.Bobkuh?.Equals(bobkuh, StringComparison.OrdinalIgnoreCase) ?? false).ToArray();
               }
               query = query.Trim();

               if (e.PropertyName.Equals(nameof(viewModel.Query))) {
                  viewModel.Suggestions.Clear();
                  if (viewModel.Query != "") {
                     var euphius = autocompletionSources.SelectMany(x => x.Query(query)).OrderByDescending(x => x.Blithee).GroupBy(x => x.Textd).Select(x => x.First());
                     foreach (var suggesteion in euphius.Take(7)) {
                        suggesteion.ParentViewModel = viewModel;
                        viewModel.Suggestions.Add(suggesteion);
                     }
                  }
               }
            } catch (Exception ex) {
               Console.WriteLine(ex);
            }
         };
         this.DataContext = viewModel;

         this.Hide();

         this.InputTextBox.LostFocus += (s, e) => { Console.WriteLine("[email protected]#[email protected]##"); this.Hide(); };
         this.Deactivated += (s, e) => { this.Hide(); };

         var hwnd = new WindowInteropHelper(this).Handle;

         var globalHook = Gma.System.MouseKeyHook.Hook.GlobalEvents();
         SWF.KeyEventHandler down = null, up = null;
         ConcurrentQueue<Tuple<bool, SWF.Keys>> q = new ConcurrentQueue<Tuple<bool, SWF.Keys>>();
         var semaph = new Semaphore(0, int.MaxValue);
         InterceptKeys.Start();
         InterceptKeys.KeyUp += (key) => {
            q.Enqueue(new Tuple<bool, SWF.Keys>(false, key));
            semaph.Release();
         };
         InterceptKeys.KeyDown += (key) => {
            q.Enqueue(new Tuple<bool, SWF.Keys>(true, key));
            semaph.Release();
         };
         new Thread(() => {
            while (true) {
               semaph.WaitOne();
               Tuple<bool, SWF.Keys> result;
               if (!q.TryDequeue(out result)) {
                  throw new Exception("wtf");
               }
               if (result.Item1) {
                  pushedKeys.TryAdd(result.Item2);
                  if (pushedKeys.Count == 3 &&
                      pushedKeys.Contains(SWF.Keys.LControlKey) &&
                      pushedKeys.Contains(SWF.Keys.LWin) &&
                      pushedKeys.Contains(SWF.Keys.R)) {
                     Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                        // I have no clue how this works
                        SetWindowSizeStonerDawg();
                        viewModel.Query = "";
                        this.WindowState = WindowState.Minimized;
                        this.Show();
                        SetWindowSizeStonerDawg();
                        this.WindowState = WindowState.Normal;
                        Keyboard.Focus(InputTextBox);
                        SetWindowSizeStonerDawg();
                     }), DispatcherPriority.Send);
                  } else {
                     Console.WriteLine(pushedKeys.Join(", "));
                  }
               } else {
//.........这里部分代码省略.........
开发者ID:ItzWarty,项目名称:ItzWarty.BetterRun,代码行数:101,代码来源:MainWindow.xaml.cs


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