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


C# ManualResetEvent.WaitOne方法代码示例

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


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

示例1: ThreadGlobalTimeServerIsShared

        public void ThreadGlobalTimeServerIsShared()
        {
            var ts1 = new TestDateTimeServer(now: new DateTime(2011, 1, 1));
            var ts2 = new TestDateTimeServer(now: new DateTime(2012, 1, 1));

            var g1 = new ManualResetEvent(false);
            var g2 = new ManualResetEvent(false);

            DateTime? t1Date = null;

            var t1 = new Thread(() => {
                DateTimeServer.SetGlobal(ts1);
                g1.WaitOne();
                t1Date = DateTimeServer.Now;
                g2.Set();
            });

            var t2 = new Thread(() => {
                DateTimeServer.SetGlobal(ts2);
                g2.Set();
                g1.WaitOne();
            });

            t1.Start();
            t2.Start();

            Assert.That(g2.WaitOne(20), Is.True);
            g2.Reset();
            g1.Set();
            Assert.That(g2.WaitOne(20), Is.True);

            Assert.That(t1Date, Is.Not.Null);
            Assert.That(t1Date, Is.EqualTo(ts2.Now));
        }
开发者ID:andy-uq,项目名称:HomeTrack,代码行数:34,代码来源:DateTimeServerTests.cs

示例2: ShouldAddNewWorkerAsynchronously

        public void ShouldAddNewWorkerAsynchronously()
        {
            RestRequest savedRequest = null;
            mockClient.Setup(trc => trc.ExecuteAsync<Worker>(It.IsAny<RestRequest>(), It.IsAny<Action<Worker>>()))
                .Callback<RestRequest, Action<Worker>>((request, action) => savedRequest = request);
            var client = mockClient.Object;
            manualResetEvent = new ManualResetEvent(false);
            var friendlyName = Twilio.Api.Tests.Utilities.MakeRandomFriendlyName();

            client.AddWorker(WORKSPACE_SID, friendlyName, "WA123", "attributes", worker =>
                {
                    manualResetEvent.Set();
                });
            manualResetEvent.WaitOne(1);

            mockClient.Verify(trc => trc.ExecuteAsync<Worker>(It.IsAny<RestRequest>(), It.IsAny<Action<Worker>>()), Times.Once);
            Assert.IsNotNull(savedRequest);
            Assert.AreEqual("Workspaces/{WorkspaceSid}/Workers", savedRequest.Resource);
            Assert.AreEqual("POST", savedRequest.Method);
            Assert.AreEqual(4, savedRequest.Parameters.Count);
            var workspaceSidParam = savedRequest.Parameters.Find(x => x.Name == "WorkspaceSid");
            Assert.IsNotNull(workspaceSidParam);
            Assert.AreEqual(WORKSPACE_SID, workspaceSidParam.Value);
            var friendlyNameParam = savedRequest.Parameters.Find(x => x.Name == "FriendlyName");
            Assert.IsNotNull(friendlyNameParam);
            Assert.AreEqual(friendlyName, friendlyNameParam.Value);
            var activitySidParam = savedRequest.Parameters.Find(x => x.Name == "ActivitySid");
            Assert.IsNotNull(activitySidParam);
            Assert.AreEqual("WA123", activitySidParam.Value);
            var attributesParam = savedRequest.Parameters.Find(x => x.Name == "Attributes");
            Assert.IsNotNull(attributesParam);
            Assert.AreEqual("attributes", attributesParam.Value);
        }
开发者ID:mrockmann,项目名称:twilio-dotnet,代码行数:33,代码来源:WorkerTests.cs

示例3: TestTimeoutOccurs

		public void TestTimeoutOccurs()
		{
			ManualResetEvent called = new ManualResetEvent(false);
			new TimeoutAction(TimeSpan.FromMilliseconds(100), delegate { called.Set(); });
			Assert.IsFalse(called.WaitOne(0, false));
			Assert.IsTrue(called.WaitOne(1000, false));
		}
开发者ID:hivie7510,项目名称:csharptest-net,代码行数:7,代码来源:TestTimeoutAction.cs

示例4: SimpleCommunication

        public void SimpleCommunication()
        {
            var reset1 = new ManualResetEvent(false);
            var reset2 = new ManualResetEvent(false);

            INatterConnection connection2 = null;
            var connection1 =_client1.OnConnected(c => reset1.Set()).OnData((c, f) => HandleResponse(f, c)).Call(GetClient2Address());
            _client2.OnConnected(c => reset2.Set()).OnData((c, f) => { HandleResponse(f, c); connection2 = c; });
            Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect");
            Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect");

            reset1.Reset();
            reset2.Reset();
            _client1.OnDisconnected(c => reset1.Set());
            _client2.OnDisconnected(c => reset2.Set());
            Send(connection1, StartNumber);

            Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect");
            Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect");
            Assert.AreEqual(ConnectionState.Disconnected, connection1.State, "Client not disconnected");
            Assert.AreEqual(ConnectionState.Disconnected, connection2.State, "Client not disconnected");

            Assert.AreEqual(EndNumber, _lastResult, "Invalid last number");
            Assert.AreEqual((EndNumber - StartNumber) + 1, _count, "Invalid count");
        }
开发者ID:KevWK314,项目名称:Natter,代码行数:25,代码来源:CommunicationTest.cs

示例5: CallbackInvokedMultipleTimes

        public void CallbackInvokedMultipleTimes()
        {
            int callbackCount = 0;
            var callbackInvoked = new ManualResetEvent(false);
            GcNotification.Register(state =>
            {
                callbackCount++;
                callbackInvoked.Set();
                if (callbackCount < 2)
                {
                    return true;
                }
                return false;
            }, null);

            GC.Collect(2, GCCollectionMode.Forced, blocking: true);
            Assert.True(callbackInvoked.WaitOne(100));
            Assert.Equal(1, callbackCount);

            callbackInvoked.Reset();

            GC.Collect(2, GCCollectionMode.Forced, blocking: true);
            Assert.True(callbackInvoked.WaitOne(100));
            Assert.Equal(2, callbackCount);

            callbackInvoked.Reset();

            // No callback expected the 3rd time
            GC.Collect(2, GCCollectionMode.Forced, blocking: true);
            Assert.False(callbackInvoked.WaitOne(100));
            Assert.Equal(2, callbackCount);
        }
开发者ID:vagelious,项目名称:ergotaxionion,代码行数:32,代码来源:GcNotificationTests.cs

示例6: Test

        public static void Test(ITransport t, IQueueStrategy strategy,
            Endpoint queueEndpoint, Action<Message> send, Func<MessageEnumerator>
            enumer)
        {
            Guid id = Guid.NewGuid();
            var serializer = new XmlMessageSerializer(new
                                                          DefaultReflection(), new DefaultKernel());

            var subscriptionStorage = new MsmqSubscriptionStorage(new
                                                                      DefaultReflection(),
                                                                  serializer,
                                                                  queueEndpoint.Uri,
                                                                  new
                                                                      EndpointRouter(),
                                                                  strategy);
            subscriptionStorage.Initialize();

            var wait = new ManualResetEvent(false);

            subscriptionStorage.SubscriptionChanged += () => wait.Set();

            t.AdministrativeMessageArrived +=
                subscriptionStorage.HandleAdministrativeMessage;

            Message msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     AddInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });
            send(msg);

            wait.WaitOne();

            msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     RemoveInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });

            wait.Reset();

            send(msg);

            wait.WaitOne();

            IEnumerable<Uri> uris = subscriptionStorage
                .GetSubscriptionsFor(typeof (TestMessage2));
            Assert.Equal(0, uris.Count());

            int count = 0;
            MessageEnumerator copy = enumer();
            while (copy.MoveNext()) count++;
            Assert.Equal(0, count);
        }
开发者ID:philiphoy,项目名称:rhino-esb,代码行数:60,代码来源:FIeldProblem_Nick.cs

示例7: ClientCancelsLimitOrder

        public void ClientCancelsLimitOrder()
        {
            OrderStatus status = OrderStatus.New;
            var manualResetEvent = new ManualResetEvent(false);

            var ib = new InteractiveBrokersBrokerage();
            ib.Connect();

            ib.OrderEvent += (sender, args) =>
            {
                status = args.Status;
                manualResetEvent.Set();
            };

            // try to sell a single share at a ridiculous price, we'll cancel this later
            var order = new Order("AAPL", SecurityType.Equity, -1, OrderType.Limit, DateTime.UtcNow, 100000);
            ib.PlaceOrder(order);
            manualResetEvent.WaitOne(2500);

            ib.CancelOrder(order);

            manualResetEvent.Reset();
            manualResetEvent.WaitOne(2500);

            Assert.AreEqual(OrderStatus.Canceled, status);
        }
开发者ID:intelliBrain,项目名称:Lean,代码行数:26,代码来源:InteractiveBrokersBrokerageTests.cs

示例8: AsyncTargetWrapperAsyncTest1

        public void AsyncTargetWrapperAsyncTest1()
        {
            var myTarget = new MyAsyncTarget();
            var targetWrapper = new AsyncTargetWrapper(myTarget);
            ((ISupportsInitialize)targetWrapper).Initialize();
            ((ISupportsInitialize)myTarget).Initialize();
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            var continuationHit = new ManualResetEvent(false);
            AsyncContinuation continuation =
                ex =>
                {
                    lastException = ex;
                    continuationHit.Set();
                };

            targetWrapper.WriteLogEvent(logEvent, continuation);

            continuationHit.WaitOne();
            Assert.IsNull(lastException);
            Assert.AreEqual(1, myTarget.WriteCount);

            continuationHit.Reset();
            targetWrapper.WriteLogEvent(logEvent, continuation);
            continuationHit.WaitOne();
            Assert.IsNull(lastException);
            Assert.AreEqual(2, myTarget.WriteCount);
        }
开发者ID:igalse,项目名称:NLog,代码行数:28,代码来源:AsyncTargetWrapperTests.cs

示例9: ShouldReceiveDelegateOnDifferentThread

        public void ShouldReceiveDelegateOnDifferentThread()
        {
            int calledThreadId = -1;
            ManualResetEvent completeEvent = new ManualResetEvent(false);
            Action<object> action = delegate
            {
                calledThreadId = Environment.CurrentManagedThreadId;
                completeEvent.Set();
            };

            IDelegateReference actionDelegateReference = new MockDelegateReference() { Target = action };
            IDelegateReference filterDelegateReference = new MockDelegateReference() { Target = (Predicate<object>)delegate { return true; } };

            var eventSubscription = new BackgroundEventSubscription<object>(actionDelegateReference, filterDelegateReference);


            var publishAction = eventSubscription.GetExecutionStrategy();

            Assert.IsNotNull(publishAction);

            publishAction.Invoke(null);
#if SILVERLIGHT || NETFX_CORE
            completeEvent.WaitOne(5000);
#else
            completeEvent.WaitOne(5000, false);
#endif
            Assert.AreNotEqual(Environment.CurrentManagedThreadId, calledThreadId);
        }
开发者ID:xperiandri,项目名称:PortablePrism,代码行数:28,代码来源:BackgroundEventSubscriptionFixture.cs

示例10: GetDistance

        public double GetDistance()
        {
            ManualResetEvent mre = new ManualResetEvent(false);
            mre.WaitOne(500);
            Stopwatch pulseLength = new Stopwatch();

            //Send pulse
            this.TriggerPin.Write(GpioPinValue.High);
            mre.WaitOne(TimeSpan.FromMilliseconds(0.01));
            this.TriggerPin.Write(GpioPinValue.Low);
            DateTime started = DateTime.Now;
            //Recieve pusle
            while (this.EchoPin.Read() == GpioPinValue.Low)
            {
                var timespan = DateTime.Now - started;
                if (timespan.TotalMilliseconds > 500.0)
                {
                    return Double.NaN;
                }
            }
            pulseLength.Start();

            while (this.EchoPin.Read() == GpioPinValue.High)
            {
            }
            pulseLength.Stop();

            //Calculating distance
            TimeSpan timeBetween = pulseLength.Elapsed;
            Debug.WriteLine(timeBetween.ToString());
            double distance = timeBetween.TotalSeconds * 17000;

            return distance;
        }
开发者ID:mmercan,项目名称:SenseHat,代码行数:34,代码来源:UltraSonic.cs

示例11: RunTest

        public void RunTest()
        {
            Console.WriteLine(String.Format("IP: {0}, port: {1}, runtime: {2} seconds, sampling interval = {3} milli", _ip.ToString(), _port.ToString(), _timeout, _interval));
            Console.WriteLine("{0}: Started, entering real-time mode...", DateTime.Now.ToString());

            SetAffinity(2);     // just because I've tested it on a duo-core...
            SetExitPoint();

            _reset = new ManualResetEvent(false);
            _csw = new CounterSenderWrapper();
            _csw.Init(_ip, _port);

            _csw.__CounterStopped += new NoParams(_csw___CounterStopped);

            _csw.StartPolling(_interval, _timeout);

            if (IsInfinite)
            {
                _reset.WaitOne();
            }
            else
            {
                if (!_reset.WaitOne(_timeout * 1000 * 2))
                { // exit without signaling
                    TryStop();
                }
            }

            Console.WriteLine("{0}: Ended, exiting real-time mode...", DateTime.Now.ToString());
            Console.WriteLine("Press any key to close this window...");
            Console.ReadKey();
        }
开发者ID:avishayp,项目名称:MccDAQCounter,代码行数:32,代码来源:Test1.cs

示例12: MockPresenter

		public MockPresenter(Page.ePageType activePageType = Page.ePageType.AVItemCollectionGallery,
			string excludedTitles = "Popular,TV,V,W,Sports,ESPN,News",
			int imageWidth = IMAGE_WIDTH, int imageHeight = IMAGE_HEIGHT)
		{
			// start logging during mocking
			SetupLogging();

			_model = MediaServerModel.GetInstance();

			TitlesExcludedFromImageReplacement = excludedTitles;
			ImageWidth = imageWidth;
			ImageHeight = imageHeight;

			AVItemCollections = new ObservableCollection<UPnPCollection>();
			AVItems = new ObservableCollection<UPnPItem>();
			DetailItem = new ObservableCollection<UPnPItem>();
			Items = new ObservableCollection<AVItemBase>();

			_allDoneEvent = new ManualResetEvent(false);
			Logger.TraceInfo(MethodBase.GetCurrentMethod(), "MockPresenter _model: {0}", _model.Actions.ContentDirectory.Name);
			_model.Actions.ContentDirectory.NewDeviceFound += NewDeviceFound;
			_model.Actions.ContentDirectory.OnCreateControlPoint(null);
			_allDoneEvent.WaitOne();
			_allDoneEvent.Reset();
			WaitTimeBetweenGetImageInMilliseconds = 0;
			StartBackgroundThreadToGetImages();
			PropertyChanged += OnLocalPropertyChanged;

			// default to the showing a collection
			ActivePageType = activePageType;
			//ActivePageType = Page.ePageType.AVItemGallery;
			//ActivePageType = Page.ePageType.AVItemDetails;

			_allDoneEvent.WaitOne(TimeSpan.FromSeconds(15D));
		}
开发者ID:CarverLab,项目名称:onCore.root,代码行数:35,代码来源:MockPresenter.cs

示例13: Run

        public void Run(ManualResetEvent stopEvent)
        {
            while (stopEvent.WaitOne(0) == false)
              {
            if (Log.IsDebugEnabled)
            {
              Log.Debug("Worker " + GetType().Name + " runs");
            }

            bool canWait;
            try
            {
              canWait = Action() == NextAction.CanWait;
            }
            catch (Exception e)
            {
              if (Log.IsErrorEnabled)
              {
            Log.Error("Error while running", e);
              }
              canWait = true;
            }

            if (canWait)
            {
              stopEvent.WaitOne(_interval);
            }
              }
        }
开发者ID:GrimaceOfDespair,项目名称:Jeremy,代码行数:29,代码来源:Worker.cs

示例14: Run

        public static void Run()
        {
            // ExStart:SupportIMAPIdleCommand
            // Connect and log in to IMAP 
            ImapClient client = new ImapClient("imap.domain.com", "username", "password");

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            ImapMonitoringEventArgs eventArgs = null;
            client.StartMonitoring(delegate(object sender, ImapMonitoringEventArgs e)
            {
                eventArgs = e;
                manualResetEvent.Set();
            });
            Thread.Sleep(2000);
            SmtpClient smtpClient = new SmtpClient("exchange.aspose.com", "username", "password");
            smtpClient.Send(new MailMessage("[email protected]", "[email protected]", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(10000);
            manualResetEvent.Reset();
            Console.WriteLine(eventArgs.NewMessages.Length);
            Console.WriteLine(eventArgs.DeletedMessages.Length);
            client.StopMonitoring("Inbox");
            smtpClient.Send(new MailMessage("[email protected]", "[email protected]", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(5000);
            // ExEnd:SupportIMAPIdleCommand
        }
开发者ID:aspose-email,项目名称:Aspose.Email-for-.NET,代码行数:25,代码来源:SupportIMAPIdleCommand.cs

示例15: AsyncTargetWrapperAsyncTest1

        public void AsyncTargetWrapperAsyncTest1()
        {
            var myTarget = new MyAsyncTarget();
            var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperAsyncTest1_Wrapper" };
            targetWrapper.Initialize(null);
            myTarget.Initialize(null);
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            var continuationHit = new ManualResetEvent(false);
            AsyncContinuation continuation =
                ex =>
                {
                    lastException = ex;
                    continuationHit.Set();
                };

            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            Assert.True(continuationHit.WaitOne());
            Assert.Null(lastException);
            Assert.Equal(1, myTarget.WriteCount);

            continuationHit.Reset();
            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            continuationHit.WaitOne();
            Assert.Null(lastException);
            Assert.Equal(2, myTarget.WriteCount);
        }
开发者ID:MikeFH,项目名称:NLog,代码行数:28,代码来源:AsyncTargetWrapperTests.cs


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