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


C# ManualResetEventSlim.Set方法代码示例

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


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

示例1: CreateWindowInstance

        private static void CreateWindowInstance(ControlTestRequest request, ManualResetEventSlim evt) {
            try {
                Window = new Window();

                if (Screen.AllScreens.Length == 1) {
                    Window.Left = 0;
                    Window.Top = 50;
                } else {
                    Screen secondary = Screen.AllScreens.FirstOrDefault(x => !x.Primary);
                    Window.Left = secondary.WorkingArea.Left;
                    Window.Top = secondary.WorkingArea.Top + 50;
                }

                Window.Width = 800;
                Window.Height = 600;

                Component = Activator.CreateInstance(request.ControlType);
                if (Component is Control) {
                    Control = Component as Control;
                } else {
                    Control = Component.GetType().GetProperty("Control").GetValue(Component) as Control;
                }

                Window.Title = "Control - " + request.ControlType;
                Window.Content = Control;
            } finally {
                evt.Set();
            }

            Window.Topmost = true;
            Window.ShowDialog();
        }
开发者ID:AlexanderSher,项目名称:RTVS-Old,代码行数:32,代码来源:ControlWindow.cs

示例2: UseSqlNotificationsIfAvailable

        public void UseSqlNotificationsIfAvailable(bool supportSqlNotifications)
        {
            // Arrange
            var sqlDependencyAdded = false;
            var retryLoopCount = 0;
            var mre = new ManualResetEventSlim();
            var dbProviderFactory = new MockDbProviderFactory();
            var dbBehavior = new Mock<IDbBehavior>();
            dbBehavior.Setup(db => db.UpdateLoopRetryDelays).Returns(_defaultRetryDelays);
            dbBehavior.Setup(db => db.StartSqlDependencyListener()).Returns(supportSqlNotifications);
            dbBehavior.Setup(db => db.AddSqlDependency(It.IsAny<IDbCommand>(), It.IsAny<Action<SqlNotificationEventArgs>>()))
                .Callback(() =>
                {
                    sqlDependencyAdded = true;
                    mre.Set();
                });
            var operation = new ObservableDbOperation("test", "test", new TraceSource("test"), dbProviderFactory, dbBehavior.Object);
            operation.Faulted += _ => mre.Set();
            operation.Queried += () =>
            {
                retryLoopCount++;
                if (retryLoopCount > 1)
                {
                    mre.Set();
                }
            };

            // Act
            ThreadPool.QueueUserWorkItem(_ => operation.ExecuteReaderWithUpdates((record, o) => { }));
            mre.Wait();
            operation.Dispose();

            // Assert
            Assert.Equal(supportSqlNotifications, sqlDependencyAdded);
        }
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:35,代码来源:ObservableSqlOperationFacts.cs

示例3: If_execution_takes_longer_than_period_it_triggers_next_execution_immediately_after_previous

 public void If_execution_takes_longer_than_period_it_triggers_next_execution_immediately_after_previous()
 {
     var counter = 0;
     var failure = false;
     var lastEndTime = DateTime.MinValue;
     var @event = new ManualResetEventSlim(false);
     var delay = TimeSpan.Zero;
     var executor = new PeriodicExecutor(() =>
     {
         delay = DateTime.Now - lastEndTime;
         if (lastEndTime != DateTime.MinValue && delay > TimeSpan.FromMilliseconds(100))
         {
             @event.Set();
             failure = true;
             return;
         }
         counter++;
         Thread.Sleep(2000);
         lastEndTime = DateTime.Now;
         if (counter == 2)
         {
             @event.Set();
         }
     }, TimeSpan.FromSeconds(1));
     executor.Start(true);
     @event.Wait();
     executor.Stop(CancellationToken.None);
     Assert.IsFalse(failure, string.Format("Time between finishing previous execution and starting this longer than {0} ms",delay));
 }
开发者ID:AlexRhees,项目名称:ServiceControl,代码行数:29,代码来源:PeriodicExecutorTests.cs

示例4: TestLeapPlayerLoop

        public void TestLeapPlayerLoop()
        {
            for (int i = 0; i < 3; i++)
            {
                var testOver = new ManualResetEventSlim();
                var timeoutTimer = new Timer(10000);

                var player = new LeapPlayer(@"frames\rotate_1.frames");
                player.LoopOutput = true;

                var bytesExpected = player.FileSizeInBytes * 3;

                Action<Frame> frameListener = frame =>
                    {
                        timeoutTimer.Stop();
                        timeoutTimer.Start();
                        if (player.TotalBytesRead >= bytesExpected)
                        {
                            testOver.Set();
                        }
                    };
                player.FrameReady += frameListener;

                timeoutTimer.Elapsed += (sender, args) => testOver.Set();
                player.StartConnection();

                timeoutTimer.Start();
                
                testOver.Wait();

                player.StopConnection();

                Assert.IsTrue(player.TotalBytesRead >= bytesExpected);
            }
        }
开发者ID:i2e-haw-hamburg,项目名称:gesture-recognition,代码行数:35,代码来源:LeapPlayerTest.cs

示例5: MemberRemovedEvent

        public void MemberRemovedEvent()
        {
            var reset = new ManualResetEventSlim();
            _client.GetCluster().AddMembershipListener(new MembershipListener
            {
                OnMemberAdded = memberAddedEvent => { reset.Set(); }
            });
            var member = StartMember(_remoteController, _cluster);
            Assert.IsTrue(reset.Wait(30 * 1000));
            reset.Reset();

            MembershipEvent memberRemovedEvent = null;
            _client.GetCluster().AddMembershipListener(new MembershipListener
            {
                OnMemberRemoved = memberRemoved =>
                {
                    memberRemovedEvent = memberRemoved;
                    reset.Set();
                }
            });
            StopMember(_remoteController, _cluster, member);

            Assert.IsTrue(reset.Wait(30*1000));
            Assert.IsInstanceOf<ICluster>(memberRemovedEvent.Source);
            Assert.IsInstanceOf<ICluster>(memberRemovedEvent.GetCluster());
            Assert.AreEqual(MembershipEvent.MemberRemoved, memberRemovedEvent.GetEventType());
            Assert.IsNotNull(memberRemovedEvent.GetMember());
            Assert.AreEqual(1, memberRemovedEvent.GetMembers().Count);
        }
开发者ID:hazelcast,项目名称:hazelcast-csharp-client,代码行数:29,代码来源:ClientClusterServiceTest.cs

示例6: Main

        /// <summary>
        /// Does all the magic of spinning up the bot.
        /// </summary>
        private static void Main()
        {
            _logger.Trace("Starting console runner");

            try
            {
                // We may actually not log to the console past this point, so let's go ahead and spam something
                // here just in case.
                Console.WriteLine("We've spun up the bot and are currently logging to our appenders. Hit CTL+C to quit.");

                // We want to know when it's ok to shutdown the bot.
                using (var shutdownManualResetEvent = new ManualResetEventSlim(false))
                {
                    // Get our application context from Spring.NET.
                    var applicationContext = ContextRegistry.GetContext();

                    // Grab our bean and spin it up.
                    var bot = applicationContext.GetObject("SpikeLite") as SpikeLite;

                    // Listen for status changes so we know when to exit
                    bot.BotStatusChanged += (sender, eventArgs) =>
                    {
                        if (eventArgs.NewStatus == BotStatus.Stopped)
                            // Signal that we're ready to shutdown the bot.
                            shutdownManualResetEvent.Set();
                    };

                    // This won't actually work while we're debugging:
                    // http://connect.microsoft.com/VisualStudio/feedback/details/524889/debugging-c-console-application-that-handles-console-cancelkeypress-is-broken-in-net-4-0
                    // Handle SIGTERM gracefully.
                    Console.CancelKeyPress += ((sender, args) =>
                    {
                        // Let us handle the shutdown of the bot
                        args.Cancel = true;

                        // Clean up.
                        bot.Shutdown("Caught SIGTERM, quitting");

                        // Signal that we're ready to shutdown the bot.
                        shutdownManualResetEvent.Set();

                        _logger.Trace("Cancel key pressed. Shutting down bot.");
                    });

                    bot.Start();

                    // Wait untill we're ready to shutdown the bot.
                    shutdownManualResetEvent.Wait();

                    _logger.Trace("Application shutting down.");

                    applicationContext.Dispose();
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat("Fatal error attempting to start the bot: {0} - {1}", ex.Message, ex.StackTrace);
            }
        }
开发者ID:pjmagee,项目名称:SpikeLite,代码行数:62,代码来源:ConsoleRunner.cs

示例7: OperateImpl

        protected override void OperateImpl(OperatingContext Context, CancellationToken CancellationToken)
        {
            using (IProgressController pc = Context.ProgressControllerFactory.CreateController(Progress))
            {
                pc.SetToIntermediate();
                pc.SetDescription(Name);
                var re = new ManualResetEventSlim(false);
                var t = new Task(() =>
                                 {
                                     while (!re.IsSet)
                                     {
                                         Context.Terminal.WriteLine();
                                         Thread.Sleep(100);
                                     }
                                 });

                Stopwatch sw = Stopwatch.StartNew();
                while (true)
                {
                    try
                    {
                        Context.Surfer.SeekForMatches(Context.Terminal, CancellationToken,
                                                      new DelegateExpectation(@"U-Boot", true, Match => t.Start()));
                        break;
                    }
                    catch (TimeoutTerminalException e)
                    {
                        if (sw.Elapsed >= _timeout)
                            throw new CanNotConnectToUBoot(e);
                    }
                }
                sw.Stop();

                Context.Surfer.SeekForMatches(Context.Terminal, CancellationToken,
                                              new DelegateExpectation(@"NAND:\s+(?<size>\d+) MB", false,
                                                                      m => Context.NandSize = ulong.Parse(m.Groups["size"].Value) * 1024 * 1024),
                                              new DelegateExpectation(@"NAND read", true,
                                                                      Match => { throw new UBootInterruptionWasSkippedDnwBurningException(); }),
                                              new DelegateExpectation(@"SMDKC100 #", true, Match =>
                                                                                           {
                                                                                               re.Set();
                                                                                               Context.Terminal.WriteLine();
                                                                                           }));
                re.Set();

                Context.Surfer.SeekForMatches(Context.Terminal, CancellationToken,
                                              new CommandExpectation(@"SMDKC100 #", Context.Terminal, "version"));
                Context.Surfer.SeekForMatches(Context.Terminal, CancellationToken,
                                              new DelegateExpectation(@"U-Boot (?<version>[\d\.]+).*\n", true,
                                                                      m => CheckUBootVersion(Version.Parse(m.Groups["version"].Value))));
                Context.State = ProgrammingContextState.UBoot;
            }
        }
开发者ID:NpoSaut,项目名称:netFirmwaring,代码行数:53,代码来源:EnterUBootOperation.cs

示例8: WaitForTransactionToComplete

        ///<summary>Blocks the current thread until the transaction completes or the timeout expires.</summary>
         public static bool WaitForTransactionToComplete(this Transaction me, TimeSpan timeout)
         {   
             Contract.Requires(me != null);

             var done = new ManualResetEventSlim();
             me.TransactionCompleted += (_, __) => done.Set();

             if(me.TransactionInformation.Status != TransactionStatus.Active)
             {
                 done.Set();
             }

             return done.Wait(timeout);
         }
开发者ID:mlidbom,项目名称:Composable.Monolithic,代码行数:15,代码来源:TransactionExtensions.cs

示例9: continuation_error_handling_then_completion

		public void continuation_error_handling_then_completion()
		{
			ManualResetEventSlim first = new ManualResetEventSlim(false),
			                     second = new ManualResetEventSlim(false),
			                     third = new ManualResetEventSlim(false);

			Exception ex = null;

			// each ContinueWith creates a new task
			var t = Task.Factory.StartNew(() =>
				{
					first.Set();
					throw new ApplicationException();
					//return -5;
				})
				.ContinueWith(tStart =>
					{
						second.Set();
						ex = tStart.Exception.InnerExceptions.First();

					}, TaskContinuationOptions.NotOnRanToCompletion)
				.ContinueWith(tStart => third.Set(), TaskContinuationOptions.OnlyOnRanToCompletion);

			t.Wait();

			Assert.IsTrue(first.IsSet);
			Assert.IsTrue(second.IsSet);
			Assert.IsTrue(third.IsSet);

			Assert.That(ex, Is.InstanceOf<ApplicationException>());
		}
开发者ID:haf,项目名称:MassTransit-AzureServiceBus,代码行数:31,代码来源:Scratch.cs

示例10: ClientStopsReconnectingAfterDisconnectTimeout

            public void ClientStopsReconnectingAfterDisconnectTimeout(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(keepAlive: 1, disconnectTimeout: 2);
                    var connection = new Client.Hubs.HubConnection(host.Url);
                    var reconnectWh = new ManualResetEventSlim();
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Reconnecting += () =>
                    {
                        reconnectWh.Set();
                        Assert.Equal(ConnectionState.Reconnecting, connection.State);
                    };

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                        Assert.Equal(ConnectionState.Disconnected, connection.State);
                    };

                    connection.Start(host.Transport).Wait();
                    host.Shutdown();

                    Assert.True(reconnectWh.Wait(TimeSpan.FromSeconds(5)));
                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(5)));
                }
            }
开发者ID:rustd,项目名称:SignalR,代码行数:28,代码来源:ConnectionFacts.cs

示例11: SubscriptionWithCancelledTaskCanBeDisposed

        public void SubscriptionWithCancelledTaskCanBeDisposed()
        {
            var dr = new DefaultDependencyResolver();
            using (var bus = new MessageBus(dr))
            {
                var subscriber = new TestSubscriber(new[] { "key" });
                var wh = new ManualResetEventSlim();

                IDisposable subscription = bus.Subscribe(subscriber, null, async (result, state) =>
                {
                    if (result.Terminal)
                    {
                        return false;
                    }

                    await Task.Delay(50);
                    var tcs = new TaskCompletionSource<bool>();
                    tcs.SetCanceled();
                    wh.Set();
                    return await tcs.Task;

                }, 10, null);

                bus.Publish("me", "key", "hello");

                wh.Wait();

                subscription.Dispose();
            }
        }
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:30,代码来源:MessageBusFacts.cs

示例12: events_raised_whilst_consuming_events_should_be_recorded

        public void events_raised_whilst_consuming_events_should_be_recorded()
        {
            var waitForConsumption = new ManualResetEventSlim(false);
            Transaction consumerTransaction = null;

            var eventStore = Substitute.For<EventStore>();

            //Because consumers run in background threads, we need to block until complete before we assert.
            eventStore.When(_ => _.LogConsumption(Arg.Any<RaisedEvent>(), Arg.Any<ConsumptionLog>())).Do(info =>
                                                                                                             {
                                                                                                                 consumerTransaction =
                                                                                                                     Transaction.Current;
                                                                                                                 waitForConsumption.Set();
                                                                                                             });

            var domain = new TestableDomain(null, null, eventStore);

            var key = "test";

            domain.Consume(
                new RaisedEvent(
                    new DogRegistered(key, null),
                    DateTimeOffset.UtcNow));

            waitForConsumption.Wait();

            var aggregateInfo = domain.AggregateTracker[typeof (Dog), key];

            ((string) aggregateInfo.Instance.AsDynamic().earbrand).ShouldEqual(key);
            aggregateInfo.Lifestate.ShouldEqual(AggregateLifestate.Live);

            var recorded = domain.TransactionTracker[consumerTransaction].RecordedEvents;
            recorded.Count().ShouldEqual(1);
            recorded.First().Event.ShouldBeType<DogIsNotVaccinated>();
        }
开发者ID:AndyHitchman,项目名称:BlastTrack,代码行数:35,代码来源:TestAggregrateRecordsEvents.cs

示例13: BasicUsageTest

		public void BasicUsageTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});
			buffer.LinkTo<int[]> (block);

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			Assert.IsFalse (evt.Wait (100));

			Assert.IsNull (array);

			Assert.IsTrue (buffer.Post (42));
			Assert.IsTrue (evt.Wait (1000));

			Assert.IsNotNull (array);
			CollectionAssert.AreEqual (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 42 }, array);
		}
开发者ID:Profit0004,项目名称:mono,代码行数:26,代码来源:BatchBlockTest.cs

示例14: TestAllow

        public void TestAllow()
        {
            var configSource = StartBootstrap("ConnectionFilter.config");
            var serverConfig = configSource.Servers.FirstOrDefault();
            var appServer = BootStrap.AppServers.FirstOrDefault() as TestServer;
            appServer.NewSessionConnected += m_Server_NewSessionConnected;

            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), serverConfig.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                TestConnectionFilter.Allow = true;
                int oldCount = TestConnectionFilter.ConnectedCount;

                var signal = new ManualResetEventSlim(false);

                ThreadPool.QueueUserWorkItem((o) =>
                    {
                        var s = o as Socket;
                        s.Connect(serverAddress);
                        signal.Set();
                    }, socket);

                Assert.IsTrue(signal.Wait(2000));
                Thread.Sleep(100);
                Assert.AreEqual(oldCount + 1, TestConnectionFilter.ConnectedCount);

                if (!m_NewSessionConnectedEvent.WaitOne(1000))
                    Assert.Fail("New session hasnot been accept on time!");
            }
        }
开发者ID:huodianyan,项目名称:SuperSocket,代码行数:31,代码来源:ConnectionFilterTest.cs

示例15: ConnectionErrorCapturesExceptionsThrownInClientHubMethod

        public void ConnectionErrorCapturesExceptionsThrownInClientHubMethod(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                var wh = new ManualResetEventSlim();
                Exception thrown = new Exception(),
                          caught = null;

                host.Initialize();

                var connection = CreateHubConnection(host);
                var proxy = connection.CreateHubProxy("ChatHub");

                proxy.On("addMessage", () =>
                {
                    throw thrown;
                });

                connection.Error += e =>
                {
                    caught = e;
                    wh.Set();
                };

                connection.Start(host.Transport).Wait();
                proxy.Invoke("Send", "");

                Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
                Assert.Equal(thrown, caught);
            }
        }
开发者ID:hallco978,项目名称:SignalR,代码行数:31,代码来源:HubProxyFacts.cs


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