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


C# BlockingQueue类代码示例

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


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

示例1: TestKitBase

        private TestKitBase(TestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName = null)
        {
            if(assertions == null) throw new ArgumentNullException("assertions");
            if(system == null)
            {
                var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig);
                system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback);
            }

            _assertions = assertions;
            _system = system;
            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(assertions));
            _testKitSettings = TestKitExtension.For(_system);
            _queue = new BlockingQueue<MessageEnvelope>();
            _log = Logging.GetLogger(system, GetType());


            var testActor = CreateTestActor(system, "testActor" + _testActorId.IncrementAndGet());
            _testActor = testActor;
            //Wait for the testactor to start
            AwaitCondition(() =>
            {
                var repRef = _testActor as RepointableRef;
                return repRef == null || repRef.IsStarted;
            }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(10));
        }
开发者ID:ClusterReply,项目名称:akka.net,代码行数:27,代码来源:TestKitBase.cs

示例2: EnqueueBeforeDequeueTest

        public void EnqueueBeforeDequeueTest()
        {
            var queue = new BlockingQueue<object>();
            var isEnqueued = new ManualResetEvent(false);
            var isDequeued = new ManualResetEvent(false);

            object value = null;

            ThreadPool.QueueUserWorkItem(_ =>
            {
                queue.Enqueue(new object());
                isEnqueued.Set();
            });
            ThreadPool.QueueUserWorkItem(_ =>
            {
                isEnqueued.WaitOne();
                value = queue.Dequeue();
                isDequeued.Set();
            });

            if (!isDequeued.WaitOne(10))
                Assert.Fail("Dequeue after Enqueue failed: Event hasn't been raised");

            if(value == null)
                Assert.Fail("Dequeue after Enqueue failed: Wrong value returned");
        }
开发者ID:kapitanov,项目名称:diploma,代码行数:26,代码来源:BlockingQueueTest.cs

示例3: MultipleInstanceMongoServerProxy

        /// <summary>
        /// Initializes a new instance of the <see cref="ShardedMongoServerProxy"/> class.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="instances">The instances.</param>
        /// <param name="connectionQueue">The state change queue.</param>
        /// <param name="connectionAttempt">The connection attempt.</param>
        /// <remarks>This constructor is used when the instances have already been instructed to connect.</remarks>
        protected MultipleInstanceMongoServerProxy(MongoServer server, IEnumerable<MongoServerInstance> instances, BlockingQueue<MongoServerInstance> connectionQueue, int connectionAttempt)
        {
            _state = MongoServerState.Connecting;
            _server = server;
            _connectedInstances = new ConnectedInstanceCollection();
            _connectionAttempt = connectionAttempt;

            _outstandingInstanceConnections = connectionQueue.Count;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                while (connectionQueue.Count > 0)
                {
                    var instance = connectionQueue.Dequeue();
                    Interlocked.Decrement(ref _outstandingInstanceConnections);
                }
            });

            // It's important to have our own copy of this list because it might get modified during iteration. 
            _instances = instances.ToList();
            foreach (var instance in instances)
            {
                instance.StateChanged += InstanceStateChanged;
                ProcessInstanceStateChange(instance);
            }
        }
开发者ID:nickgervasi,项目名称:mongo-csharp-driver,代码行数:33,代码来源:MultipleInstanceMongoServerProxy.cs

示例4: Receiver

 static Receiver()
 {
     if (rcvBlockingQ == null)
         rcvBlockingQ = new BlockingQueue<SvcMsg>();
     if (rcvBlockingQServer == null)
         rcvBlockingQServer = new BlockingQueue<SvcMsg>();
 }
开发者ID:karantech9,项目名称:Dependency-Analyzer,代码行数:7,代码来源:Server.cs

示例5: JabberNetwork

        public JabberNetwork(SocialUser user, byte[] certData, 
      BlockingQueue queue, string jabber_port)
        {
            _local_user = user;
              _queue = queue;
              _friends = new Dictionary<string, List<string>>();
              _online = false;
              _auth_pending = false;
              _pres_sent = false;
              _jclient = new JabberClient();

              _jclient.Port = Int32.Parse(jabber_port);
              _jclient.AutoReconnect = 30F;
              _jclient.AutoStartTLS = true;
              _jclient.KeepAlive = 30F;
              _jclient.AutoPresence = false;
              _jclient.AutoRoster = false;
              _jclient.LocalCertificate = null;
              _jclient.Resource = SVPNRESOURCE +
            _local_user.Fingerprint.Substring(0, 10);

              _jclient.OnError += HandleOnError;
              _jclient.OnAuthError += HandleOnAuthError;

            #if SVPN_NUNIT
              _jclient.OnReadText += HandleOnReadText;
              _jclient.OnWriteText += HandleOnWriteText;
            #endif
              _jclient.OnAuthenticate += HandleOnAuthenticate;
              _jclient.OnPresence += HandleOnPresence;
              _jclient.OnIQ += HandleOnIQ;
              _jclient.OnInvalidCertificate += HandleInvalidCert;
        }
开发者ID:j3g,项目名称:socialvpn,代码行数:33,代码来源:JabberNetwork.cs

示例6: EventQueue

        public EventQueue(IVsStatusbar statusBar)
        {
            this._statusBar = statusBar;
            _queue = new BlockingQueue<Action>();

            _queueTask = Task.Run(() => ProcessQueue());
        }
开发者ID:ChinaJason,项目名称:Typewriter,代码行数:7,代码来源:EventQueue.cs

示例7: LocalAssetServer

        public LocalAssetServer()
        {
            bool yapfile;
            this._assetRequests = new BlockingQueue<ARequest>();
            yapfile = System.IO.File.Exists("assets.yap");

            OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Local Asset Server class created");
            try
            {
                db = Db4oFactory.OpenFile("assets.yap");
                OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Db4 Asset database  creation");
            }
            catch (Exception e)
            {
                db.Close();
                OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Db4 Asset server :Constructor - Exception occured");
                OpenSim.Framework.Console.MainConsole.Instance.WriteLine(e.ToString());
            }
            if (!yapfile)
            {
                this.SetUpAssetDatabase();
            }
            this._localAssetServerThread = new Thread(new ThreadStart(RunRequests));
            this._localAssetServerThread.IsBackground = true;
            this._localAssetServerThread.Start();
        }
开发者ID:BackupTheBerlios,项目名称:ulife-svn,代码行数:26,代码来源:LocalAssetServer.cs

示例8: Many_consumers_with_timeouts

 public void Many_consumers_with_timeouts()
 {
     BlockingQueue<string> q = new BlockingQueue<string>();
     Thread c1 = new Thread(MultiConsumer);
     Thread c2 = new Thread(MultiConsumer);
     Thread c3 = new Thread(MultiConsumer);
     c1.IsBackground = true;
     c2.IsBackground = true;
     c3.IsBackground = true;
     Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v1
         = new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>(q, "x", TimeSpan.FromSeconds(1), new ManualResetEvent(false));
     c1.Start(v1);
     Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v2
         = new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>(q, "x", TimeSpan.FromSeconds(1), new ManualResetEvent(false));
     c2.Start(v2);
     Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v3
         = new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>(q, "x", TimeSpan.FromSeconds(1), new ManualResetEvent(false));
     c3.Start(v3);
     q.Enqueue("foo");
     Assert.IsTrue(v1.Item4.WaitOne(2000, false), "thread 1 did not finish");
     Assert.IsTrue(v2.Item4.WaitOne(2000, false), "thread 2 did not finish");
     Assert.IsTrue(v3.Item4.WaitOne(2000, false), "thread 3 did not finish");
     bool gotValue = false;
     foreach(Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v in new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>[] { v1, v2, v3 }) {
         if(v.Item2 == "foo") {
             gotValue = true;
             Assert.Less(v.Item3.TotalSeconds, 1);
         } else {
             Assert.IsNull(v.Item2);
             Assert.GreaterOrEqual(v.Item3.TotalSeconds, 0.95);
         }
     }
     Assert.IsTrue(gotValue);
 }
开发者ID:nataren,项目名称:DReAM,代码行数:34,代码来源:BlockingQueueTests.cs

示例9: BeginGet

 public virtual string BeginGet(string key) {
   BlockingQueue q  = new BlockingQueue();
   this._dht.AsGet(key, q);
   string tk = this.GenToken(key);
   this._bqs.Add(tk, q);
   return tk;
 }
开发者ID:xujyan,项目名称:brunet,代码行数:7,代码来源:DhtAdapter.cs

示例10: StaSynchronizationContext

 public StaSynchronizationContext()
     : base()
 {
     mQueue = new BlockingQueue<SendOrPostCallbackItem>();
      mStaThread = new StaThread(mQueue);
      mStaThread.Start();
 }
开发者ID:OpenSharp,项目名称:NDceRpc,代码行数:7,代码来源:StaSynchronizationContext.cs

示例11: EventQueueServer

 public EventQueueServer(HttpListener server)
 {
     this.server = server;
     eventQueue = new BlockingQueue<EventQueueEvent>();
     running = true;
     currentID = 1;
 }
开发者ID:RavenB,项目名称:gridsearch,代码行数:7,代码来源:EventQueueServer.cs

示例12: BackgroundWorker

        public BackgroundWorker()
        {
            _queue = new BlockingQueue<Action>();
            _cancellationTokenSource = new CancellationTokenSource();

            Start();
        }
开发者ID:jpalmero9,项目名称:peer2net,代码行数:7,代码来源:BackgroundWorker.cs

示例13: BackendManager

        public BackendManager(string backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
        {
            m_options = options;
            m_backendurl = backendurl;
            m_statwriter = statwriter;
            m_taskControl = statwriter as BasicResults;
            m_db = new DatabaseCollector(database, statwriter);

            m_backend = DynamicLoader.BackendLoader.GetBackend(m_backendurl, m_options.RawOptions);
            if (m_backend == null)
                throw new Exception(string.Format("Backend not supported: {0}", m_backendurl));

            if (!m_options.NoEncryption)
            {
                m_encryption = DynamicLoader.EncryptionLoader.GetModule(m_options.EncryptionModule, m_options.Passphrase, m_options.RawOptions);
                if (m_encryption == null)
                    throw new Exception(string.Format("Encryption method not supported: ", m_options.EncryptionModule));
            }

            if (m_taskControl != null)
                m_taskControl.StateChangedEvent += (state) => {
                    if (state == TaskControlState.Abort)
                        m_thread.Abort();
                };
            m_queue = new BlockingQueue<FileEntryItem>(options.SynchronousUpload ? 1 : (options.AsynchronousUploadLimit == 0 ? int.MaxValue : options.AsynchronousUploadLimit));
            m_thread = new System.Threading.Thread(this.ThreadRun);
            m_thread.Name = "Backend Async Worker";
            m_thread.IsBackground = true;
            m_thread.Start();
        }
开发者ID:Berimor66,项目名称:duplicati,代码行数:30,代码来源:BackendManager.cs

示例14: TestKitBase

        private TestKitBase(TestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName, string testActorName)
        {
            if(assertions == null) throw new ArgumentNullException("assertions");
            if(system == null)
            {
                var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig);
                system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback);
            }

            _assertions = assertions;
            _system = system;
            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(assertions));
            _testKitSettings = TestKitExtension.For(_system);
            _queue = new BlockingQueue<MessageEnvelope>();
            _log = Logging.GetLogger(system, GetType());
            _eventFilterFactory = new EventFilterFactory(this);
            if (string.IsNullOrEmpty(testActorName))
                testActorName = "testActor" + _testActorId.IncrementAndGet();

            var testActor = CreateTestActor(system, testActorName);
            //Wait for the testactor to start
            AwaitCondition(() =>
            {
                var repRef = testActor as RepointableRef;
                return repRef == null || repRef.IsStarted;
            }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));

            if(!(this is NoImplicitSender))
            {
                InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)testActor).Underlying;
            }
            _testActor = testActor;

        }
开发者ID:rodrigovidal,项目名称:akka.net,代码行数:35,代码来源:TestKitBase.cs

示例15: TestBlockingQueueStress

        public void TestBlockingQueueStress()
        {
            var queue = new BlockingQueue<int>(1);

            var rnd = new ThreadLocal<Random>(() => new Random());
            var generatedTotal = 0;
            var consummedTotal = 0;

            var producers = TestMonitorSimple.RunSimultanously(5, () =>
            {
                for (var i = 0; i < 1e6; i++)
                {
                    var value = rnd.Value.Next(100);
                    Interlocked.Add(ref generatedTotal, value);
                    queue.AddIfNotCompleted(value);
                }
            }, false);

            var consumers = TestMonitorSimple.RunSimultanously(5, () =>
            {
                foreach (var value in queue.GetConsumingEnumerable())
                {
                    Interlocked.Add(ref consummedTotal, value);
                }
            }, false);

            producers.ForEach(t => t.Join());
            queue.CompleteAdding();

            consumers.ForEach(t => t.Join());

            Assert.IsTrue(consummedTotal == generatedTotal);
        }
开发者ID:mamitko,项目名称:GZipTest,代码行数:33,代码来源:TestParallellizing.cs


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