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


C# ManualResetEventSlim.Reset方法代码示例

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


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

示例1: BasicUsageTest

		public void BasicUsageTest()
		{
			Tuple<IList<int>, IList<int>> result = null;
			var evt = new ManualResetEventSlim (false);

			var actionBlock = new ActionBlock<Tuple<IList<int>, IList<int>>> (r =>
			{
				result = r;
				evt.Set ();
			});
			var block = new BatchedJoinBlock<int, int> (2);

			block.LinkTo (actionBlock);

			// both targets once
			Assert.IsTrue (block.Target1.Post (1));

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

			Assert.IsTrue (block.Target2.Post (2));

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

			Assert.IsNotNull (result);
			CollectionAssert.AreEqual (new[] { 1 }, result.Item1);
			CollectionAssert.AreEqual (new[] { 2 }, result.Item2);

			result = null;
			evt.Reset ();

			// target 1 twice
			Assert.IsTrue (block.Target1.Post (3));

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

			Assert.IsTrue (block.Target1.Post (4));
			Assert.IsTrue (evt.Wait (100));

			Assert.IsNotNull (result);
			CollectionAssert.AreEqual (new[] { 3, 4 }, result.Item1);
			CollectionAssert.IsEmpty (result.Item2);

			result = null;
			evt.Reset ();

			// target 2 twice
			Assert.IsTrue (block.Target2.Post (5));

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

			Assert.IsTrue (block.Target2.Post (6));
			Assert.IsTrue (evt.Wait (100));

			Assert.IsNotNull (result);
			CollectionAssert.IsEmpty (result.Item1);
			CollectionAssert.AreEqual (new[] { 5, 6 }, result.Item2);
		}
开发者ID:nlhepler,项目名称:mono,代码行数:60,代码来源:BatchedJoinBlockTest.cs

示例2: SuccessiveTimeoutTest

        public void SuccessiveTimeoutTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var mre = new ManualResetEventSlim(false);
                host.Initialize(keepAlive: 5, messageBusType: messageBusType);
                var connection = CreateConnection(host, "/my-reconnect");

                using (connection)
                {
                    connection.Reconnected += () =>
                    {
                        mre.Set();
                    };

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

                    ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromMilliseconds(500));

                    // Assert that Reconnected is called
                    Assert.True(mre.Wait(TimeSpan.FromSeconds(15)));

                    // Assert that Reconnected is called again
                    mre.Reset();
                    Assert.True(mre.Wait(TimeSpan.FromSeconds(15)));

                    // Clean-up
                    mre.Dispose();
                }
            }
        }
开发者ID:RyanChristensen,项目名称:SignalR,代码行数:32,代码来源:KeepAliveFacts.cs

示例3: FunWithMRE

        private static void FunWithMRE()
        {
            ManualResetEventSlim mre = new ManualResetEventSlim();
            //MRE mre = new MRE();
            mre.WaitAsync().ContinueWith(t => CW("Wait 1 complete"));
            mre.WaitAsync().ContinueWith(t => CW("Wait 2 complete"));
            mre.WaitAsync().ContinueWith(t => CW("Wait 3 complete"));

            WaitUntilKey("set");

            mre.Set();

            mre.WaitAsync().ContinueWith(t => CW("Wait 4 complete"));
            mre.WaitAsync().ContinueWith(t => CW("Wait 5 complete"));
            mre.WaitAsync().ContinueWith(t => CW("Wait 6 complete"));



            //WaitUntilKey("reset");
            mre.Reset();

            mre.WaitAsync().ContinueWith(t => CW("Wait 7 complete"));
            mre.WaitAsync().ContinueWith(t => CW("Wait 8 complete"));
            mre.WaitAsync().ContinueWith(t => CW("Wait 9 complete"));

            WaitUntilKey("set again");

            mre.Set();

        }
开发者ID:adbk,项目名称:spikes,代码行数:30,代码来源:Program.cs

示例4: 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

示例5: RunManualResetEventSlimTest0_StateTrans

        // Validates init, set, reset state transitions.
        private static void RunManualResetEventSlimTest0_StateTrans(bool init)
        {
            ManualResetEventSlim ev = new ManualResetEventSlim(init);
            if (ev.IsSet != init)
            {
                Debug.WriteLine("* RunManualResetEventSlimTest0_StateTrans(init={0})", init);
                Assert.True(false, string.Format("  > FAILED.  expected IsSet=={0}, but it's {1}", init, ev.IsSet));
            }

            for (int i = 0; i < 50; i++)
            {
                ev.Set();
                if (!ev.IsSet)
                {
                    Debug.WriteLine("* RunManualResetEventSlimTest0_StateTrans(init={0})", init);
                    Assert.True(false, string.Format("  > FAILED.  expected IsSet, but it's false"));
                }

                ev.Reset();
                if (ev.IsSet)
                {
                    Debug.WriteLine("* RunManualResetEventSlimTest0_StateTrans(init={0})", init);
                    Assert.True(false, string.Format("  > FAILED.  expected !IsSet, but it's true"));
                }
            }
        }
开发者ID:johnhhm,项目名称:corefx,代码行数:27,代码来源:ManualResetEventSlimTests.cs

示例6: TestTimerStartAutoReset

        public void TestTimerStartAutoReset()
        {
            using (var timer = new TestTimer(1))
            {
                var mres = new ManualResetEventSlim();
                int count = 0;
                int target = 1;

                timer.AutoReset = false;
                timer.Elapsed += (sender, e) =>
                {
                    if (Interlocked.Increment(ref count) == target)
                    {
                        mres.Set();
                    }
                };
                timer.Start();

                mres.Wait();
                Assert.False(timer.Enabled, "Auto-reset timer should not be enabled after elapsed");
                Assert.Equal(1, count);

                count = 0;
                target = 10;
                mres.Reset();
                timer.AutoReset = true;
                mres.Wait();

                timer.Stop();
                Assert.InRange(count, target, int.MaxValue);
            }
        }
开发者ID:Corillian,项目名称:corefx,代码行数:32,代码来源:TimerTests.cs

示例7: Main

        static void Main(string[] args)
        {
            // create the primtive
            ManualResetEventSlim manualResetEvent
                = new ManualResetEventSlim();

            // create the cancellation token source
            CancellationTokenSource tokenSource
                = new CancellationTokenSource();

            // create and start the task that will wait on the event
            Task waitingTask = Task.Factory.StartNew(() => {
                while (true) {
                    // wait on the primitive
                    manualResetEvent.Wait(tokenSource.Token);
                    // print out a message
                    Console.WriteLine("Waiting task active");
                }
            }, tokenSource.Token);

            // create and start the signalling task
            Task signallingTask = Task.Factory.StartNew(() => {
                // create a random generator for sleep periods
                Random rnd = new Random();
                // loop while the task has not been cancelled
                while (!tokenSource.Token.IsCancellationRequested) {
                    // go to sleep for a random period
                    tokenSource.Token.WaitHandle.WaitOne(rnd.Next(500, 2000));
                    // set the event
                    manualResetEvent.Set();
                    Console.WriteLine("Event set");
                    // go to sleep again
                    tokenSource.Token.WaitHandle.WaitOne(rnd.Next(500, 2000));
                    // reset the event
                    manualResetEvent.Reset();
                    Console.WriteLine("Event reset");
                }
                // if we reach this point, we know the task has been cancelled
                tokenSource.Token.ThrowIfCancellationRequested();
            }, tokenSource.Token);

            // ask the user to press return before we cancel
            // the token and bring the tasks to an end
            Console.WriteLine("Press enter to cancel tasks");
            Console.ReadLine();

            // cancel the token source and wait for the tasks
            tokenSource.Cancel();
            try {
                Task.WaitAll(waitingTask, signallingTask);
            } catch (AggregateException) {
                // discard exceptions
            }

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
开发者ID:clp-takekawa,项目名称:codes-from-books,代码行数:58,代码来源:Listing_16.cs

示例8: Run

        public override void Run(VoidAction tickCallback)
        {
            // 59.75 is sort of compensation
            long ticksPerFrame = (int)Math.Round(MyGameTimer.Frequency / 59.75f);
            long targetTicks = 0;

            MyLog.Default.WriteLine("Timer Frequency: " + MyGameTimer.Frequency);
            MyLog.Default.WriteLine("Ticks per frame: " + ticksPerFrame);

            ManualResetEventSlim waiter = new ManualResetEventSlim(false, 0);
            MyTimer.TimerEventHandler handler = new MyTimer.TimerEventHandler((a, b, c, d, e) =>
            {
                waiter.Set();
            });


            base.Run(delegate
            {
                using (Stats.Generic.Measure("WaitForUpdate"))
                {
                    var currentTicks = m_gameTimer.ElapsedTicks;

                    // Wait for correct frame start
                    targetTicks += ticksPerFrame;
                    if (currentTicks > targetTicks + ticksPerFrame * 5)
                    {
                        // We're more behind than 5 frames, don't try to catch up
                        targetTicks = currentTicks;
                    }
                    else
                    {
                        // For until correct tick comes
                        if (MyFakes.ENABLE_UPDATE_WAIT)
                        {
                            var remaining = MyTimeSpan.FromTicks(targetTicks - currentTicks);
                            int waitMs = (int)(remaining.Miliseconds - 0.1); // To handle up to 0.1ms inaccuracy of timer
                            if (waitMs > 0)
                            {
                                waiter.Reset();
                                MyTimer.StartOneShot(waitMs, handler);
                                waiter.Wait(17); // Never wait more than 17ms
                                //Debug.Assert(MyPerformanceCounter.ElapsedTicks < targetTicks);
                                //VRageRender.MyRenderStats.Write("WaitRemaining", (float)MyPerformanceCounter.TicksToMs(targetTicks - MyPerformanceCounter.ElapsedTicks), VRageRender.MyStatTypeEnum.MinMaxAvg, 300, 3);
                            }
                        }
                        while (m_gameTimer.ElapsedTicks < targetTicks) ;
                    }
                }

                //UpdateInternal();
                tickCallback();

                ProfilerShort.Commit();
            });
        }
开发者ID:Krulac,项目名称:SpaceEngineers,代码行数:55,代码来源:FixedRenderLoop.cs

示例9: Execute

        public void Execute()
        {
            //
            // 通常の使い方.
            //
            var mres = new ManualResetEventSlim(false);

            ThreadPool.QueueUserWorkItem(DoProc, mres);

            Output.Write("メインスレッド待機中・・・");
            mres.Wait();
            Output.WriteLine("終了");

            //
            // WaitメソッドにCancellationTokenを受け付けるオーバーロードを使用。
            //
            mres.Reset();

            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            Task.Factory.StartNew(DoProc, mres);

            //
            // キャンセル状態に設定.
            //
            tokenSource.Cancel();

            Output.Write("メインスレッド待機中・・・");

            try
            {
                //
                // CancellationTokenを指定して、Wait呼び出し。
                // この場合は、以下のどちらかの条件を満たした時点でWaitが解除される。
                //  ・別の場所にて、Setが呼ばれてシグナル状態となる。
                //  ・CancellationTokenがキャンセルされる。
                //
                // トークンがキャンセルされた場合、OperationCanceledExceptionが発生するので
                // CancellationTokenを指定するWaitを呼び出す場合は、try-catchが必須となる。
                //
                // 今回の例の場合は、予めCancellationTokenをキャンセルしているので
                // タスク処理でシグナル状態に設定されるよりも先に、キャンセル状態に設定される。
                // なので、実行結果には、「*** シグナル状態に設定 ***」という文言は出力されない。
                //
                mres.Wait(token);
            }
            catch (OperationCanceledException cancelEx)
            {
                Output.Write("*** {0} *** ", cancelEx.Message);
            }

            Output.WriteLine("終了");
        }
开发者ID:devlights,项目名称:Sazare,代码行数:54,代码来源:ManualResetEventSlimSamples01.cs

示例10: LatestOfSource

        public void LatestOfSource()
        {
            var source = AsyncEnumerable.Source<int>();
            var latest = source.Latest();

            var step = new ManualResetEventSlim(false);
            var proceed = new ManualResetEventSlim(false);

            Assert.IsTrue(latest.Item.IsNone, $"(0) {latest.Item}");

            var t = Task.Run(async () =>
            {
                await source.Yield(1);
                await Task.Yield();
                step.Set();
                proceed.Wait(); proceed.Reset();

                await source.Yield(2);
                await Task.Yield();
                step.Set();
                proceed.Wait(); proceed.Reset();

                await source.Break();
                await Task.Yield();
                step.Set();
                proceed.Wait(); proceed.Reset();
            });

            step.Wait(); step.Reset();
            Assert.IsTrue(latest.Item.Value == 1, $"(1) {latest.Item}");
            proceed.Set();

            step.Wait(); step.Reset();
            Assert.IsTrue(latest.Item.Value == 2, $"(2) {latest.Item}");
            proceed.Set();

            step.Wait(); step.Reset();
            Assert.IsTrue(latest.Item.IsCompleted, $"(3) {latest.Item}");
            proceed.Set();
        }
开发者ID:krauthaufen,项目名称:System.Collections.Async,代码行数:40,代码来源:LatestTests.cs

示例11: MemcacheClientReplicasTest

        public void MemcacheClientReplicasTest()
        {
            var callbackMutex = new ManualResetEventSlim(false);

            var client = new MemcacheClient(_configuration);

            // The number of requests sent is capped by the number of nodes in the cluster.
            // The last iteration of the loop below actually tests the case where the total
            // number of copies (Replicas+1) is strictly greater than the number of nodes.
            int nodeCount = _configuration.NodesEndPoints.Count;
            for (int replicas = 0; replicas <= nodeCount; replicas++)
            {
                _configuration.Replicas = replicas;

                // SET
                callbackMutex.Reset();
                NodeMock.TrySendCounter = 0;
                Assert.IsTrue(client.Set("toto", new byte[0], TimeSpan.MaxValue, s => callbackMutex.Set()));
                Assert.AreEqual(Math.Min(replicas + 1, nodeCount), NodeMock.TrySendCounter);
                Assert.IsTrue(callbackMutex.Wait(1000),
                    string.Format("The SET callback has not been received after 1 second (Replicas = {0})", replicas));

                // GET
                callbackMutex.Reset();
                NodeMock.TrySendCounter = 0;
                Assert.IsTrue(client.Get("toto", (Status s, byte[] data) => callbackMutex.Set()));
                Assert.AreEqual(Math.Min(replicas + 1, nodeCount), NodeMock.TrySendCounter);
                Assert.IsTrue(callbackMutex.Wait(1000),
                    string.Format("The GET callback has not been received after 1 second (Replicas = {0})", replicas));

                // DELETE
                callbackMutex.Reset();
                NodeMock.TrySendCounter = 0;
                Assert.IsTrue(client.Delete("toto", s => callbackMutex.Set()));
                Assert.AreEqual(Math.Min(replicas + 1, nodeCount), NodeMock.TrySendCounter);
                Assert.IsTrue(callbackMutex.Wait(1000),
                    string.Format("The DELETE callback has not been received after 1 second (Replicas = {0})", replicas));

            }
        }
开发者ID:mindis,项目名称:memcache-driver,代码行数:40,代码来源:ReplicasTests.cs

示例12: ShipsViewModel

        public ShipsViewModel()
        {
            WaitShipsEvent = new ManualResetEventSlim(false);

            KanColleGame.Current.ObservablePropertyChanged.Where(r => r == nameof(KanColleGame.Current.Ships)).Subscribe(_ =>
            {
                Count = KanColleGame.Current.Ships.Count + KanColleGame.Current.DroppedShip;

                WaitShipsEvent.Reset();
                Ships = KanColleGame.Current.Ships.Values.Select(r => new ShipViewModel(r)).ToArray();
                WaitShipsEvent.Set();
            });
        }
开发者ID:XHidamariSketchX,项目名称:ProjectDentan,代码行数:13,代码来源:ShipsViewModel.cs

示例13: NextOfSource

        public void NextOfSource()
        {
            var source = AsyncEnumerable.Source<int>();
            var next = source.Next();

            var step = new ManualResetEventSlim(false);
            var proceed = new ManualResetEventSlim(false);
            
            var t = Task.Run(async () =>
            {
                await source.Yield(1);
                await Task.Yield();
                step.Set();
                proceed.Wait(); proceed.Reset();

                await source.Yield(2);
                await Task.Yield();
                step.Set();
                proceed.Wait(); proceed.Reset();

                await source.Break();
                await Task.Yield();
                step.Set();
                proceed.Wait(); proceed.Reset();
            });

            step.Wait(); step.Reset();
            Assert.IsTrue(next.Result == 1, $"(1) {next.Result}");
            next = source.Next();
            proceed.Set();

            step.Wait(); step.Reset();
            Assert.IsTrue(next.Result == 2, $"(2) {next.Result}");
            next = source.Next();
            proceed.Set();

            step.Wait(); step.Reset();
        }
开发者ID:krauthaufen,项目名称:System.Collections.Async,代码行数:38,代码来源:NextTests.cs

示例14: Set_Reset_Cycles

        public void Set_Reset_Cycles()
        {
            using (var resetEvent = new ManualResetEventSlim(false))
            {
                var stopwatch = Stopwatch.StartNew();

                for (var i = 0; i < Iterations; i++)
                {
                    resetEvent.Set();
                    resetEvent.Reset();
                }
                stopwatch.StopAndLog(Iterations);
            }
        }
开发者ID:hanswolff,项目名称:benchmark,代码行数:14,代码来源:ManualResetEventSlimTests.cs

示例15: HarvesterProcessingDispatcher

        public HarvesterProcessingDispatcher(ILogger logger, Func<IFileBatchManager> fileBatchManagerFactory, string harvesterName)
        {
            _logger = logger;
            _harvesterName = harvesterName;
            _fileBatchManagerFactory = fileBatchManagerFactory;

            _operationQueue = new Queue<BasicSerializedDeliveryEventArgs<FileMessage>>();
            _shutdownEvent = new ManualResetEventSlim(false);
            _shutdownEvent.Reset();

            _dispatcher = new Task(this.Processing, TaskCreationOptions.LongRunning);
            _dispatcher.Start();

            _syncObject = new object();
        }
开发者ID:RamanBut-Husaim,项目名称:.NET-Practice,代码行数:15,代码来源:HarvesterProcessingDispatcher.cs


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