System.Collections.Concurrent.ConcurrentBag.ToArray()

Here are the examples of the csharp api class System.Collections.Concurrent.ConcurrentBag.ToArray() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

32 Examples 7

1. Example

Project: orleans
Source File: LegacyOrleansLoggerProvider.cs
public ILogger CreateLogger(string categoryName)
        {
            return new LegacyOrleansLogger(categoryName, this.LogConsumers.ToArray(), ipEndPoint);
        }

2. Example

Project: referencesource
Source File: ConcurrentBag.cs
[OnSerializing]
        private void OnSerializing(StreamingContext context)
        {
            // save the data into the serialization array to be saved
            m_serializationArray = ToArray();
        }

3. Example

Project: RedDog
Source File: FluentMessageRegistration.cs
public Type[] GetTypes()
        {
            return _messageTypes.ToArray();
        }

4. Example

Project: ChromeDevTools
Source File: ChromeSession.cs
private void HandleEvent(IEvent evnt)
        {
            if (null == evnt
                || null == evnt)
            {
                return;
            }
            var type = evnt.GetType().GetGenericArguments().FirstOrDefault();
            if (null == type)
            {
                return;
            }
            var handlerKey = type.FullName;
            ConcurrentBag<Action<object>> handlers = null;
            if (_handlers.TryGetValue(handlerKey, out handlers))
            {
                var localHandlers = handlers.ToArray();
                foreach (var handler in localHandlers)
                {
                    ExecuteHandler(handler, evnt);
                }
            }
        }

5. Example

Project: roslyn
Source File: NavigateToTestAggregator.Callback.cs
public IEnumerable<NavigateToItem> GetItemsSynchronously()
            {
                _doneCalled.WaitOne();
                var items = _itemsReceived.ToArray();

                NavigateToItem dummy;
                while (_itemsReceived.TryTake(out dummy))
                {
                    // do nothing.
                }

                return items;
            }

6. Example

Project: inVtero.net
Source File: inVtero.cs
public ScanResult[] YaraAll(string RulesFile, bool IncludeData = false, bool KernelSpace = false)
        {
            ConcurrentBag<ScanResult> rv = new ConcurrentBag<ScanResult>(); 

            Parallel.ForEach<DetectedProc>(Processes, proc =>
            {
                var doKernel = (proc.CR3Value == KernelProc.CR3Value);

                using (proc.MemAccess = new Mem(MemAccess))
                {
                    var prv = proc.YaraScan(RulesFile, IncludeData, false);
                    foreach (var r in prv)
                        rv.Add(r);

                    if (Vtero.VerboseLevel > 0)
                        WriteColor(ConsoleColor.Cyan, $"Done yara on proc {proc}, {prv.Count} signature matches.");
                }
            });

            return rv.ToArray();
        }

7. Example

Project: azure-webjobs-sdk
Source File: SharedQueueWatcher.cs
public void Notify(string enqueuedInQueueName)
        {
            ConcurrentBag<INotificationCommand> queueRegistrations;

            if (_registrations.TryGetValue(enqueuedInQueueName, out queueRegistrations))
            {
                foreach (INotificationCommand registration in queueRegistrations.ToArray())
                {
                    registration.Notify();
                }
            }
        }

8. Example

Project: PowerShellAudio
Source File: WindowSelector.cs
internal float GetResult()
        {
            // Select the best representative value from the 95th percentile:
            float[] unsortedWindows = _rmsWindows.ToArray();
            float averageEnergy = unsortedWindows.OrderBy(item => item)
                .ElementAt((int)Math.Ceiling(unsortedWindows.Length * _rmsPercentile) - 1);

            // Subtract from the perceived loudness of pink noise at 89dB to get the recommended adjustment:
            return _pinkNoiseReference - averageEnergy;
        }

9. Example

Project: StopGuessing
Source File: Cache.cs
public void RecoverSpace(int numberOfItemsToRemove)
        {
            // Remove the least-recently-accessed values from the cache
            KeyValuePair<TKey, TValue>[] entriesToRemove = RemoveAndGetLeastRecentlyAccessed(numberOfItemsToRemove).ToArray();

            ConcurrentBag<Task> asyncDisposalTasks = new ConcurrentBag<Task>();

            // Call the disposal method on each class.
            Parallel.For(0, entriesToRemove.Length, (counter, loop) =>
            {
                KeyValuePair<TKey, TValue> entryToRemove = entriesToRemove[counter];
                TValue valueToRemove = entryToRemove.Value;
                
                // ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull
                if (valueToRemove is IAsyncDisposable)
                {
                    asyncDisposalTasks.Add(((IAsyncDisposable)valueToRemove).DisposeAsync());
                }
                else if (valueToRemove is IDisposable)
                {
                    ((IDisposable)valueToRemove).Dispose();
                }

                // Remove the last reference to the value so that it can be garbage collected immediately.
                entriesToRemove[counter] = default(KeyValuePair<TKey, TValue>);
            });

            Task.WaitAll(asyncDisposalTasks.ToArray());
        }

10. Example

Project: StopGuessing
Source File: Cache.cs
public void RecoverSpace(int numberOfItemsToRemove)
        {
            // Remove the least-recently-accessed values from the cache
            KeyValuePair<TKey, TValue>[] entriesToRemove = RemoveAndGetLeastRecentlyAccessed(numberOfItemsToRemove).ToArray();

            ConcurrentBag<Task> asyncDisposalTasks = new ConcurrentBag<Task>();

            // Call the disposal method on each class.
            Parallel.For(0, entriesToRemove.Length, (counter, loop) =>
            {
                KeyValuePair<TKey, TValue> entryToRemove = entriesToRemove[counter];
                TValue valueToRemove = entryToRemove.Value;
                
                // ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull
                if (valueToRemove is IAsyncDisposable)
                {
                    asyncDisposalTasks.Add(((IAsyncDisposable)valueToRemove).DisposeAsync());
                }
                else if (valueToRemove is IDisposable)
                {
                    ((IDisposable)valueToRemove).Dispose();
                }

                // Remove the last reference to the value so that it can be garbage collected immediately.
                entriesToRemove[counter] = default(KeyValuePair<TKey, TValue>);
            });

            Task.WaitAll(asyncDisposalTasks.ToArray());
        }

11. Example

Project: dotnet-apiport
Source File: ProjectAnalyzer.cs
public async Task AnalyzeProjectAsync(ICollection<Project> projects, CancellationToken cancell/n ..... /n //View Source file for more details /n }

12. Example

Project: dotnet-apiport
Source File: DefaultProjectBuilder.cs
public virtual async Task<bool> BuildAsync(IEnumerable<Project> projects)
        {
    /n ..... /n //View Source file for more details /n }

13. Example

Project: PatternFinder
Source File: Pattern.cs
public static Signature[] Scan(byte[] data, Signature[] signatures)
        {
            var found = new ConcurrentBag<Signature>();
            Parallel.ForEach(signatures, signature =>
            {
                if (Find(data, signature.Pattern, out signature.FoundOffset))
                    found.Add(signature);
            });
            return found.ToArray();
        }

14. Example

Project: Easy.Common
Source File: ThreadLocalDisposable.cs
public void Dispose()
        {
            _threadLocal.Dispose();
            Array.ForEach(_values.ToArray(), v => v.Dispose());
        }

15. Example

Project: inVtero.net
Source File: inVtero.cs
public void Dispose(bool disposing)
        {
            if (!disposedValue && (ConfOpts != null && !ConfOpts.IgnoreSaveData))
                CheckpointSaveState();

            if (!disposedValue && disposing)
            {
                if (Processes != null)
                {
                    // kernelproc is included in this
                    var procs = Processes.ToArray();


                    for (int i = 0; i < procs.Count(); i++)
                    {
                        procs[i].Dispose();
                        procs[i] = null;
                    }

                    // these should all be somewhat shared to the same objects
                    Processes = null;
                    AddressSpace = null;
                    KernelProc = null;
                    ASGroups = null;
                    VMCSs = null;
                    procs = null;
                }
                if (MemAccess != null)
                    ((IDisposable)MemAccess).Dispose();
                if (PFNBitmap == null)
                    ((IDisposable)PFNBitmap).Dispose();


                MemAccess = null;
                PFNBitmap = null;
            }
            disposedValue = true;
        }

16. Example

Project: Craig-s-Utility-Library
Source File: TagDictionary.cs
public bool Remove(Key key)
        {
            var ReturnValue = ContainsKey(key);
            Items = new ConcurrentBag<TaggedItem<Key, Value>>(Items.ToArray(x => x).Where(x => !x.Keys.Contains(key)));
            KeyList.Remove(key);
            return ReturnValue;
        }

17. Example

Project: Craig-s-Utility-Library
Source File: TagDictionary.cs
public bool Remove(Key key)
        {
            var ReturnValue = ContainsKey(key);
            Items = new ConcurrentBag<TaggedItem<Key, Value>>(Items.ToArray(x => x).Where(x => !x.Keys.Contains(key)));
            KeyList.Remove(key);
            return ReturnValue;
        }

18. Example

Project: revenj
Source File: NotifyHub.cs
public override Task OnDisconnected()
		{
			ConcurrentBag<Type> types;
			if (Connections.TryRemove(Context.ConnectionId, out types))
			{
				foreach (var t in types.ToArray())
				{
					ConcurrentDictionary<string, IDisposable> dict;
					IDisposable disp;
					if (Listeners.TryGetValue(t, out dict) && dict.TryRemove(Context.ConnectionId, out disp))
						disp.Dispose();
				}
			}
			return base.OnDisconnected();
		}

19. Example

Project: DotNetRuleEngine
Source File: AsyncRuleService.cs
public async Task<IRuleResult[]> GetAsyncRuleResultsAsync()
        {
            await Task.WhenAll(_parallelRuleResults);

            Parallel.ForEach(_parallelRuleResults, rule =>
            {
                rule.Result.AssignRuleName(rule.GetType().Name);
                AddToAsyncRuleResults(rule.Result);
            });

            return _asyncRuleResults.ToArray();
        }

20. Example

Project: CodeContracts
Source File: Parallel.cs
public void RunWithBuckets(string[] args)
    {
      Contract.Requires(args != null);

      args = RemoveArgs(args); // To make cccheck.exe happy

      var watch = new CustomStopwatch();
      watch.Start();

      var executor = new BucketExecutor();
//      var id = 0;

      var temp = new ConcurrentBag<IEnumerable<int>>();

//      foreach(var bucket in this.GenerateDisjointBuckets())
      Parallel.ForEach(
        this.GenerateDisjointBuckets(),
      bucket =>
      {
        //PrintBucket(watch, bucket);

        temp.Add(bucket);
        // executor.AddJob(() => RunOneAnalysis(id++, args, ToSelectArgument(bucket)));      
      });

      var array = temp.ToArray();

      Console.WriteLine("Eventually we inferred {0} buckets", array.Count());
      foreach(var b in array)
      {
        PrintBucket(watch, b);
      }

      //executor.DoAllTheRemainingJobs();

      //executor.WaitForStillActiveJobs();
    }

21. Example

Project: revenj
Source File: NotifyHub.cs
public override Task OnDisconnected(bool stopCalled)
		{
			TraceSource.TraceEvent(TraceEventType.Verbose, 1102, "Disconnected: {0}", Context.ConnectionId);
			ConcurrentBag<Type> types;
			if (Connections.TryRemove(Context.ConnectionId, out types))
			{
				foreach (var t in types.ToArray())
				{
					ConcurrentDictionary<string, IDisposable> dict;
					IDisposable disp;
					if (Listeners.TryGetValue(t, out dict) && dict.TryRemove(Context.ConnectionId, out disp))
						disp.Dispose();
				}
			}
			return base.OnDisconnected(stopCalled);
		}

22. Example

Project: netmq
Source File: NetMQPollerTest.cs
[Fact]
        public void TwoThreads()
        {
            int count1 = 0;
            int count2 = 0;

            var allTasks = new ConcurrentBag<Task>();

            using (var poller = new NetMQPoller())
            {
                poller.RunAsync();

                Task t1 = Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 100; i++)
                    {
                        var task = new Task(() => { count1++; });
                        allTasks.Add(task);
                        task.Start(poller);
                    }
                });

                Task t2 = Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 100; i++)
                    {
                        var task = new Task(() => { count2++; });
                        allTasks.Add(task);
                        task.Start(poller);
                    }
                });

                t1.Wait(1000);
                t2.Wait(1000);
                Task.WaitAll(allTasks.ToArray(), 1000);

                Assert.Equal(100, count1);
                Assert.Equal(100, count2);
            }
        }

23. Example

Project: helios
Source File: TcpServerSocketChannelStateMachine.cs
protected override ITcpServerSocketModel RunInternal(ITcpServerSocketModel obj0)
            {
     /n ..... /n //View Source file for more details /n }

24. Example

Project: CodeContracts
Source File: Parallel.cs
public IEnumerable<IEnumerable<int>> GenerateDisjointBuckets()
    {

      var bucketsC/n ..... /n //View Source file for more details /n }

25. Example

Project: ConanExilesServerUpdater
Source File: GeneralServices.cs
public void StartServices()
        {
            _cancellationTokenSource = new CancellationTokenSo/n ..... /n //View Source file for more details /n }

26. Example

Project: box-windows-sdk-v2
Source File: BoxEventsManagerTestIntegration.cs
[TestMethod]
        public async Task LongPollUserEvents_LiveSession()
        {
            const /n ..... /n //View Source file for more details /n }

27. Example

Project: Scripty
Source File: Program.cs
private int Run(string[] args)
        {
            // Parse the command line if there are args
   /n ..... /n //View Source file for more details /n }

28. Example

Project: ServiceProxy
Source File: Program.cs
static async Task SimpleBenchmark(IFooService fooService)
        {
            var nCalls = 100 * 1000;

            var random = new Random();

            var tasksToWait = new ConcurrentBag<Task>();

            var sw = Stopwatch.StartNew();

            Parallel.For(0, nCalls, i =>
            {
                //gets a foo with id between 1 and 10, asynchronously
                tasksToWait.Add(
                    fooService.GetFooAsync(random.Next(1, 11)));
            });

            await Task.WhenAll(tasksToWait.ToArray());

            sw.Stop();

            Console.WriteLine("{0} calls completed in {1}", nCalls, sw.Elapsed);
            Console.WriteLine("Avg time per call: {0} ms", (double)sw.ElapsedMilliseconds / nCalls);
            Console.WriteLine("Requests per second: {0}", (double)nCalls / sw.Elapsed.TotalSeconds);
        }

29. Example

Project: Rosalia
Source File: ParallelExecutionStrategy.cs
public ITaskResult<IdentityWithResult[]> Execute(Layer layer, Func<Identity, TaskContext> contextFactory, ITaskInterceptor interceptor)
        {
            ITaskResult<IdentityWithResult[]> failure = null;

            var results = new ConcurrentBag<IdentityWithResult>();
            var layerTasks = layer.Items.Select(item => SystemTask.Factory.StartNew(() =>
            {
                Identity id = item.Id;
                TaskContext taskContext = contextFactory(id);

                if (interceptor != null)
                {
                    interceptor.BeforeTaskExecute(id, item.Task, taskContext);
                }
                
                ITaskResult<object> result = item.Task.Execute(taskContext);
                if (interceptor != null)
                {
                    interceptor.AfterTaskExecute(id, item.Task, taskContext, result);
                }

                if (result.IsSuccess)
                {
                    results.Add(new IdentityWithResult(id, result.Data));
                }
                else
                {
                    failure = new FailureResult<IdentityWithResult[]>(result.Error);
                }
            })).ToArray();

            SystemTask.WaitAll(layerTasks);

            if (failure != null)
            {
                return failure;
            }

            return new SuccessResult<IdentityWithResult[]>(results.ToArray());
        }

30. Example

Project: LappaORM
Source File: EntityBuilder.cs
public TEntity[] CreateEntities<TEntity>(DbDataReader dataReader, QueryBuilder<TEntity> /n ..... /n //View Source file for more details /n }

31. Example

Project: inVtero.net
Source File: DetectedProc.cs
public void MergeVAMetaData(bool DoStackCheck = false)
        {
            // setup kernel in opti/n ..... /n //View Source file for more details /n }

32. Example

Project: NuGet.Extensions
Source File: Get.cs
private void GetByDirectoryPath(IFileSystem baseFileSystem, string target)
        {
            if /n ..... /n //View Source file for more details /n }