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

C# BlockingCollection类代码示例

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

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



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

示例1: AsynchronousTraceListenerWrapper

        /// <summary>
        /// Initializes a new instance of the <see cref="AsynchronousTraceListenerWrapper" /> class.
        /// </summary>
        /// <param name="wrappedTraceListener">The wrapped trace listener.</param>
        /// <param name="ownsWrappedTraceListener">Indicates whether the wrapper should dispose the wrapped trace listener.</param>
        /// <param name="bufferSize">Size of the buffer for asynchronous requests.</param>
        /// <param name="maxDegreeOfParallelism">The max degree of parallelism for thread safe listeners. Specify <see langword="null"/> to use the current core count.</param>
        /// <param name="disposeTimeout">The timeout for waiting to complete buffered requests when disposing. When <see langword="null" /> the default of <see cref="Timeout.InfiniteTimeSpan" /> is used.</param>
        public AsynchronousTraceListenerWrapper(
            TraceListener wrappedTraceListener,
            bool ownsWrappedTraceListener = true,
            int? bufferSize = DefaultBufferSize,
            int? maxDegreeOfParallelism = null,
            TimeSpan? disposeTimeout = null)
        {
            Guard.ArgumentNotNull(wrappedTraceListener, "wrappedTraceListener");
            CheckBufferSize(bufferSize);
            CheckMaxDegreeOfParallelism(maxDegreeOfParallelism);
            CheckDisposeTimeout(disposeTimeout);

            this.wrappedTraceListener = wrappedTraceListener;
            this.ownsWrappedTraceListener = ownsWrappedTraceListener;
            this.disposeTimeout = disposeTimeout ?? Timeout.InfiniteTimeSpan;

            this.closeSource = new CancellationTokenSource();
            this.requests = bufferSize != null ? new BlockingCollection<Action<TraceListener>>(bufferSize.Value) : new BlockingCollection<Action<TraceListener>>();

            if (this.wrappedTraceListener.IsThreadSafe)
            {
                this.maxDegreeOfParallelism = maxDegreeOfParallelism.HasValue ? maxDegreeOfParallelism.Value : Environment.ProcessorCount;
                this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequestsInParallel, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
            else
            {
                this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequests, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
        }
开发者ID:Brar,项目名称:entlib,代码行数:37,代码来源:AsynchronousTraceListenerWrapper.cs


示例2: Do

		/// <summary>
		/// Do the specified input and output.
		/// </summary>
		/// <param name="input">Input.</param>
		/// <param name="output">Output.</param>
        public void Do(BlockingCollection<ISkeleton> input, Action<IEnumerable<Result>> fireNewCommand)
        {
            var data = new Dictionary<JointType, InputVector>();
            foreach (var skeleton in input.GetConsumingEnumerable())
            {
                foreach (var joint in skeleton.Joints)
                {
                    if (!data.ContainsKey(joint.JointType))
                    {
                        data.Add(joint.JointType, new InputVector());
                    }
                    data[joint.JointType].Stream.Add(joint.Point);
                }
                if (data.First().Value.Stream.Count < 5)
                {
                    continue;
                }
                var results = Recognizer.Recognize(data);
                try
                {
                    fireNewCommand(results);
                }
                catch (Exception)
                {
                    if (data.First().Value.Stream.Count > 40)
                    {
                        data.Clear();
                    }
                    continue;
                }
                data.Clear();
            }
        }
开发者ID:i2e-haw-hamburg,项目名称:gesture-recognition,代码行数:38,代码来源:RecognitionTask.cs


示例3: CommandProcessor

 public CommandProcessor(BlockingCollection<Job> allJobs, Scheduler scheduler, JobQueue jobQueue, QueueProcessor queueProcessor)
 {
     _allJobs = allJobs;
     _scheduler = scheduler;
     _jobQueue = jobQueue;
     _queueProcessor = queueProcessor;
 }
开发者ID:VictorGavrish,项目名称:MentoringD2D3,代码行数:7,代码来源:CommandProcessor.cs


示例4: VideoClass

 public VideoClass(string url, string languageCode)
 {
     Url = url;
     Subtitles = new BlockingCollection<SubtitlesClass>();
     Language = TEDdownloader.Language.GetLanguage(languageCode);
     LanguageCode = languageCode;
 }
开发者ID:gaiverrr,项目名称:TEDdownloader,代码行数:7,代码来源:VideoClass.cs


示例5: Main

        static void Main(string[] args)
        {
            Console.WriteLine("=== In Line Execution ===");

            Task<string>[] tasks = GetTasks();

            string[] all = Task.WhenAll(tasks).Result;

            Console.WriteLine(string.Join("", all));

            Console.WriteLine("=== Standard Live Execution ===");

            tasks = GetTasks();

            BlockingCollection<string> results = new BlockingCollection<string>();

            Task.WaitAll(tasks.Select(async t =>
                {
                    results.Add(await t);
                    Console.WriteLine("[{0:hh:mm:ss.fff}] Current result: [{1}]", DateTime.Now, string.Join("", results));
                }).ToArray());

            Console.WriteLine("=== Pragmateek Live Execution ===");

            results = new BlockingCollection<string>();

            tasks = GetTasks();

            Task.WaitAll(tasks.Select(t => t.ContinueWith(p =>
                {
                    results.Add(p.Result);
                    Console.WriteLine("[{0:hh:mm:ss.fff}] Current result: [{1}]", DateTime.Now, string.Join("", results));
                })).ToArray());
        }
开发者ID:PragmateekTraining,项目名称:FormationProgrammationParallele,代码行数:34,代码来源:Program.cs


示例6: TestWritableTransportServer

        public void TestWritableTransportServer()
        {
            BlockingCollection<WritableString> queue = new BlockingCollection<WritableString>();
            List<string> events = new List<string>();

            IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
            var remoteHandler = Observer.Create<TransportEvent<WritableString>>(tEvent => queue.Add(tEvent.Data));

            using (var server = new WritableTransportServer<WritableString>(endpoint, remoteHandler, _tcpPortProvider, _injector))
            {
                server.Run();

                IPEndPoint remoteEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), server.LocalEndpoint.Port);
                using (var client = new WritableTransportClient<WritableString>(remoteEndpoint, _injector))
                {
                    client.Send(new WritableString("Hello"));
                    client.Send(new WritableString(", "));
                    client.Send(new WritableString("World!"));

                    events.Add(queue.Take().Data);
                    events.Add(queue.Take().Data);
                    events.Add(queue.Take().Data);
                } 
            }

            Assert.AreEqual(3, events.Count);
            Assert.AreEqual(events[0], "Hello");
            Assert.AreEqual(events[1], ", ");
            Assert.AreEqual(events[2], "World!");
        }
开发者ID:kijungs,项目名称:incubator-reef,代码行数:30,代码来源:WritableTransportTest.cs


示例7: BlockingCollectionQueue

 public BlockingCollectionQueue()
 {
     _writerQueue = new BlockingCollection<User>();
     _readerQueue = new BlockingCollection<User>();
     _currentQueue = _writerQueue;
     Task.Factory.StartNew(() => ConsumerFunc(), TaskCreationOptions.None);
 }
开发者ID:yjqGitHub,项目名称:DoubleQueueTest,代码行数:7,代码来源:BlockingCollectionQueue.cs


示例8: HardDiskCache

 public HardDiskCache(string cachePath)
 {
     CachePath = cachePath;
     indexList = new List<LocationInfo>();
     imageQueue = new BlockingCollection<Image>();
     StartConsumerThread();
 }
开发者ID:TreeSeed,项目名称:ShareX,代码行数:7,代码来源:ScreenRecorderCache.cs


示例9: GetLogQueue

 public static BlockingCollection<LogMsg> GetLogQueue()
 {
     if (m_logQueue == null) {
         m_logQueue = new BlockingCollection<LogMsg> ();
     }
     return m_logQueue;
 }
开发者ID:smc314,项目名称:helix,代码行数:7,代码来源:Log.cs


示例10: TestStreamingOneWayCommunication

        public void TestStreamingOneWayCommunication()
        {
            IPAddress listeningAddress = IPAddress.Parse("127.0.0.1");

            BlockingCollection<string> queue = new BlockingCollection<string>();
            List<string> events = new List<string>();
            IStreamingCodec<string> codec = TangFactory.GetTang().NewInjector().GetInstance<StringStreamingCodec>();

            using (var remoteManager1 = _remoteManagerFactory1.GetInstance<string>(listeningAddress, codec))
            using (var remoteManager2 = _remoteManagerFactory1.GetInstance<string>(listeningAddress, codec))
            {
                var observer = Observer.Create<string>(queue.Add);
                IPEndPoint endpoint1 = new IPEndPoint(listeningAddress, 0);
                remoteManager2.RegisterObserver(endpoint1, observer);

                var remoteObserver = remoteManager1.GetRemoteObserver(remoteManager2.LocalEndpoint);
                remoteObserver.OnNext("abc");
                remoteObserver.OnNext("def");
                remoteObserver.OnNext("ghi");

                events.Add(queue.Take());
                events.Add(queue.Take());
                events.Add(queue.Take());
            }

            Assert.AreEqual(3, events.Count);
        }
开发者ID:priyankporwal,项目名称:incubator-reef,代码行数:27,代码来源:StreamingRemoteManagerTest.cs


示例11: CanGetNotificationAboutDocumentPut

		public void CanGetNotificationAboutDocumentPut()
		{
			using(GetNewServer())
			{using (var store = new DocumentStore
			{
				Url = "http://localhost:8079",
				Conventions =
					{
						FailoverBehavior = FailoverBehavior.FailImmediately
					}
			}.Initialize())
			{
				var list = new BlockingCollection<DocumentChangeNotification>();
				var taskObservable = store.Changes();
				taskObservable.Task.Wait();
				var observableWithTask = taskObservable.ForDocument("items/1");
				observableWithTask.Task.Wait();
				observableWithTask.Subscribe(list.Add);

				using (var session = store.OpenSession())
				{
					session.Store(new Item(), "items/1");
					session.SaveChanges();
				}

				DocumentChangeNotification documentChangeNotification;
				Assert.True(list.TryTake(out documentChangeNotification, TimeSpan.FromSeconds(3)));

				Assert.Equal("items/1", documentChangeNotification.Id);
				Assert.Equal(documentChangeNotification.Type, DocumentChangeTypes.Put);
				Assert.NotNull(documentChangeNotification.Etag);
			}
				Thread.Sleep(1000);
			}
		}
开发者ID:randacc,项目名称:ravendb,代码行数:35,代码来源:ClientServer.cs


示例12: OutBuffer

 public OutBuffer(int maxSizeAsPowerOfTwo)
 {
     //_completeds = new BlockingCollection<TaskCompleted>((int)Math.Pow(2, maxSizeAsPowerOfTwo));
     //This is for output, and not spcifying the size revert to ConcurrentQueue.
     //Bounding slows down considerably. Should remove when ring array in place.
     _completeds = new BlockingCollection<TaskCompleted>();
 }
开发者ID:heartysoft,项目名称:res,代码行数:7,代码来源:OutBuffer.cs


示例13: TestOneWayCommunicationClientOnly

        public void TestOneWayCommunicationClientOnly()
        {
            IPAddress listeningAddress = IPAddress.Parse("127.0.0.1");

            BlockingCollection<string> queue = new BlockingCollection<string>();
            List<string> events = new List<string>();

            using (var remoteManager1 = _remoteManagerFactory.GetInstance(new StringCodec()))
            using (var remoteManager2 = _remoteManagerFactory.GetInstance(listeningAddress, new StringCodec()))
            {
                IPEndPoint remoteEndpoint = new IPEndPoint(listeningAddress, 0);
                var observer = Observer.Create<string>(queue.Add);
                remoteManager2.RegisterObserver(remoteEndpoint, observer);

                var remoteObserver = remoteManager1.GetRemoteObserver(remoteManager2.LocalEndpoint);
                remoteObserver.OnNext("abc");
                remoteObserver.OnNext("def");
                remoteObserver.OnNext("ghi");

                events.Add(queue.Take());
                events.Add(queue.Take());
                events.Add(queue.Take());
            }

            Assert.Equal(3, events.Count);
        }
开发者ID:LastOne817,项目名称:reef,代码行数:26,代码来源:RemoteManagerTest.cs


示例14: DefaultActionExecutionService

 /// <summary>Parameterized constructor.
 /// </summary>
 /// <param name="loggerFactory"></param>
 public DefaultActionExecutionService(ILoggerFactory loggerFactory)
 {
     _logger = loggerFactory.Create(GetType().Name);
     _actionQueue = new BlockingCollection<ActionInfo>(new ConcurrentQueue<ActionInfo>());
     _worker = new Worker(TryTakeAndExecuteAction, DefaultPeriod);
     _worker.Start();
 }
开发者ID:jaohaohsuan,项目名称:ecommon,代码行数:10,代码来源:DefaultActionExecutionService.cs


示例15: Reducer

 /// <summary>
 /// Constructor
 /// </summary>
 public Reducer()
 {
     _distinctWordList = new ConcurrentDictionary<string, int>();
     var concurrentBag = new ConcurrentBag<string>();
     _wordChunks = new BlockingCollection<string>(concurrentBag);
     Numwords = 0;
 }
开发者ID:JordiCorbilla,项目名称:MapReduce,代码行数:10,代码来源:Reducer.cs


示例16: CanGetNotificationAboutDocumentDelete

        public void CanGetNotificationAboutDocumentDelete()
        {
            using (GetNewServer())
            using (var store = new DocumentStore
            {
                Url = "http://localhost:8079"
            }.Initialize())
            {
                var list = new BlockingCollection<DocumentChangeNotification>();
                var taskObservable = store.Changes();
                taskObservable.Task.Wait();
                var observableWithTask = taskObservable.ForDocument("items/1");
                observableWithTask.Task.Wait();
                observableWithTask
                    .Where(x => x.Type == DocumentChangeTypes.Delete)
                    .Subscribe(list.Add);

                using (var session = store.OpenSession())
                {
                    session.Store(new Item(), "items/1");
                    session.SaveChanges();
                }

                store.DatabaseCommands.Delete("items/1", null);

                DocumentChangeNotification DocumentChangeNotification;
                Assert.True(list.TryTake(out DocumentChangeNotification, TimeSpan.FromSeconds(2)));

                Assert.Equal("items/1", DocumentChangeNotification.Id);
                Assert.Equal(DocumentChangeNotification.Type, DocumentChangeTypes.Delete);

                ((RemoteDatabaseChanges) taskObservable).DisposeAsync().Wait();
            }
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:34,代码来源:ClientServer.cs


示例17: CanGetNotificationAboutDocumentIndexUpdate

        public void CanGetNotificationAboutDocumentIndexUpdate()
        {
            using (var server = GetNewServer())
            using (var store = NewRemoteDocumentStore(ravenDbServer: server))
            {
                var list = new BlockingCollection<IndexChangeNotification>();
                var taskObservable = store.Changes();
                taskObservable.Task.Wait();
                var observableWithTask = taskObservable.ForIndex("Raven/DocumentsByEntityName");
                observableWithTask.Task.Wait();
                observableWithTask
                    .Subscribe(list.Add);

                using (var session = store.OpenSession())
                {
                    session.Store(new Item(), "items/1");
                    session.SaveChanges();
                }

                IndexChangeNotification indexChangeNotification;
                Assert.True(list.TryTake(out indexChangeNotification, TimeSpan.FromSeconds(5)));

                Assert.Equal("Raven/DocumentsByEntityName", indexChangeNotification.Name);
                Assert.Equal(indexChangeNotification.Type, IndexChangeTypes.MapCompleted);
            }
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:26,代码来源:ClientServer.cs


示例18: CAudioPlayer

 public CAudioPlayer()
 {
     _effects = new BlockingCollection<CSound>();
     System.Threading.ThreadStart threadStarter = _checkForThingsToPlay;
     _audioThread = new Thread(threadStarter);
     _audioThread.Start();
 }
开发者ID:shadowkami,项目名称:King-of-Thieves,代码行数:7,代码来源:CAudioPlayer.cs


示例19: StaTaskScheduler

        /// <summary>Initializes a new instance of the StaTaskScheduler class with the specified concurrency level.</summary>
        /// <param name="numberOfThreads">The number of threads that should be created and used by this scheduler.</param>
        public StaTaskScheduler(int numberOfThreads)
        {
            // Validate arguments
            if (numberOfThreads < 1) throw new ArgumentOutOfRangeException("concurrencyLevel");

            // Initialize the tasks collection
            _tasks = new BlockingCollection<Task>();

            // Create the threads to be used by this scheduler
            _threads = Enumerable.Range(0, numberOfThreads).Select(i =>
                       {
                           var thread = new Thread(() =>
                           {
                               // Continually get the next task and try to execute it.
                               // This will continue until the scheduler is disposed and no more tasks remain.
                               foreach (var t in _tasks.GetConsumingEnumerable())
                               {
                                   TryExecuteTask(t);
                               }
                           });
                           thread.IsBackground = true;
                           thread.SetApartmentState(ApartmentState.STA);
                           return thread;
                       }).ToList();

            // Start all of the threads
            _threads.ForEach(t => t.Start());
        }
开发者ID:bevacqua,项目名称:Swarm,代码行数:30,代码来源:StaTaskScheduler.cs


示例20: MTATaskScheduler

        /// <summary>Initializes a new instance of the MTATaskScheduler class with the specified concurrency level.</summary>
        /// <param name="numberOfThreads">The number of threads that should be created and used by this scheduler.</param>
        /// <param name="nameFormat">The template name form to use to name threads.</param>
        public MTATaskScheduler(int numberOfThreads, string nameFormat)
        {
            // Validate arguments
            if (numberOfThreads < 1) throw new ArgumentOutOfRangeException("numberOfThreads");

            // Initialize the tasks collection
            tasks = new BlockingCollection<Task>();

            // Create the threads to be used by this scheduler
            _threads = Enumerable.Range(0, numberOfThreads).Select(i =>
                       {
                           var thread = new Thread(() =>
                           {
                               // Continually get the next task and try to execute it.
                               // This will continue until the scheduler is disposed and no more tasks remain.
                               foreach (var t in tasks.GetConsumingEnumerable())
                               {
                                   TryExecuteTask(t);
                               }
                           })
                           {
                               IsBackground = true
                           };
                           thread.SetApartmentState(ApartmentState.MTA);
                           thread.Name = String.Format("{0} - {1}", nameFormat, thread.ManagedThreadId);
                           return thread;
                       }).ToList();

            // Start all of the threads
            _threads.ForEach(t => t.Start());
        }
开发者ID:ramonsmits,项目名称:NServiceBus.Gateway,代码行数:34,代码来源:MTATaskScheduler.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# BlockingQueue类代码示例发布时间:2022-05-24
下一篇:
C# BlockVariable类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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