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


C# BlockingCollection类代码示例

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


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


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