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


C# ManualResetEventSlim.Wait方法代码示例

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


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

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

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

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

示例4: BasicUsageTest

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

			var ablock = new ActionBlock<Tuple<int, int>> (t =>
			{
				tuple = t;
				evt.Set ();
			});
			var block = new JoinBlock<int, int> ();
			block.LinkTo (ablock);

			block.Target1.Post (42);

			evt.Wait (1000);
			Assert.IsNull (tuple);

			block.Target2.Post (24);

			evt.Wait ();
			Assert.IsNotNull (tuple);
			Assert.AreEqual (42, tuple.Item1);
			Assert.AreEqual (24, tuple.Item2);
		}
开发者ID:Profit0004,项目名称:mono,代码行数:25,代码来源:JoinBlockTest.cs

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

示例6: BasicUsageTest

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

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

			block.LinkTo (actionBlock);

			// all targets once
			Assert.IsTrue (block.Target1.Post (1));
			Assert.IsTrue (block.Target2.Post (2));

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

			Assert.IsTrue (block.Target3.Post ("foo"));

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

			Assert.IsNotNull (result);
			CollectionAssert.AreEqual (new[] { 1 }, result.Item1);
			CollectionAssert.AreEqual (new[] { 2 }, result.Item2);
			CollectionAssert.AreEqual (new[] { "foo" }, result.Item3);
		}
开发者ID:Profit0004,项目名称:mono,代码行数:31,代码来源:BatchedJoinBlock`3Test.cs

示例7: PushTryPop

        public void PushTryPop(int producerThreads, int consumerThreads)
        {
            var stack = new ConcurrentStack<int>();
            var startEvent = new ManualResetEventSlim(false);
            var finished = 0;
            var stop = false;
            var producerTasks = Enumerable.Range(0, producerThreads).Select(i => Task.Factory.StartNew(() =>
                {
                    var count = iterations/producerThreads;
                    startEvent.Wait();
                    for (var j = 0; j < count; j++)
                        stack.Push(0);
                    Interlocked.Increment(ref finished);
                    if (finished >= producerThreads) stop = true;
                }, TaskCreationOptions.LongRunning)).ToArray();
            var consumerTasks = Enumerable.Range(0, consumerThreads).Select(i => Task.Factory.StartNew(() =>
                {
                    int num;
                    startEvent.Wait();
                    while (!stop) stack.TryPop(out num);
                }, TaskCreationOptions.LongRunning)).ToArray();

            var stopwatch = Stopwatch.StartNew();
            startEvent.Set();
            stop = true;
            Task.WaitAll(producerTasks);
            Task.WaitAll(consumerTasks);
            stopwatch.StopAndLog(iterations);
        }
开发者ID:hanswolff,项目名称:benchmark,代码行数:29,代码来源:ConcurrentStackTest.cs

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

示例9: ETradeDispatcher

		public ETradeDispatcher(Action<Exception> errorHandler)
			: base(errorHandler)
		{
			const int num = 2; //num of Add() calls below
			var count = 0;
			var done = new ManualResetEventSlim(false);
			Action report = delegate
			{
				if (Interlocked.Increment(ref count) == num)
					done.Set();
			};
			int idmain, iddom;

			idmain = iddom = 0;

			Add(() =>
			{
				idmain = Thread.CurrentThread.ManagedThreadId;
				report();
			}, _eventThreadRequestName);

			Add(() =>
			{
				iddom = Thread.CurrentThread.ManagedThreadId;
				report();
			}, _eventThreadResponseName);

			done.Wait();

			_eventThreadRequestId = idmain;
			_eventThreadResponseId = iddom;
		}
开发者ID:RakotVT,项目名称:StockSharp,代码行数:32,代码来源:ETradeDispatcher.cs

示例10: OpenCalledOnConnectionRestored

        public void OpenCalledOnConnectionRestored()
        {
            int openInvoked = 0;
            var wh = new ManualResetEventSlim();

            var redisConnection = GetMockRedisConnection();

            var redisMessageBus = new Mock<RedisMessageBus>(GetDependencyResolver(), new RedisScaleoutConfiguration(String.Empty, String.Empty),
                redisConnection.Object) { CallBase = true };

            redisMessageBus.Setup(m => m.OpenStream(It.IsAny<int>())).Callback(() =>
            {
                // Open would be called twice - once when connection starts and once when it is restored
                if (++openInvoked == 2)
                {
                    wh.Set();
                }
            });

            // Creating an instance to invoke the constructor which starts the connection
            var instance = redisMessageBus.Object;

            redisConnection.Raise(mock => mock.ConnectionRestored += null, new Exception());

            Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
        }
开发者ID:kietnha,项目名称:SignalR,代码行数:26,代码来源:RedisMessageBusFacts.cs

示例11: MarkActiveStopsConnectionIfCalledAfterExtendedPeriod

        public void MarkActiveStopsConnectionIfCalledAfterExtendedPeriod(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);
                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                    };

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

                    // The MarkActive interval should check the reconnect window. Since this is short it should force the connection to disconnect.
                    ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(1);

                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
                }
            }
        }
开发者ID:kietnha,项目名称:SignalR,代码行数:25,代码来源:ConnectionFacts.cs

示例12: CanInvokeMethodsAndReceiveMessagesFromValidTypedHub

        public async Task CanInvokeMethodsAndReceiveMessagesFromValidTypedHub(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                using (var connection = CreateHubConnection(host))
                {
                    var hub = connection.CreateHubProxy("ValidTypedHub");
                    var echoTcs = new TaskCompletionSource<string>();
                    var pingWh = new ManualResetEventSlim();

                    hub.On<string>("Echo", message => echoTcs.TrySetResult(message));
                    hub.On("Ping", pingWh.Set);

                    await connection.Start(host.TransportFactory());

                    hub.InvokeWithTimeout("Echo", "arbitrary message");
                    Assert.True(echoTcs.Task.Wait(TimeSpan.FromSeconds(10)));
                    Assert.Equal("arbitrary message", echoTcs.Task.Result);

                    hub.InvokeWithTimeout("Ping");
                    Assert.True(pingWh.Wait(TimeSpan.FromSeconds(10)));
                }
            }
        }
开发者ID:GaneshBachhao,项目名称:SignalR,代码行数:26,代码来源:TypedHubFacts.cs

示例13: ConnectRetriesOnError

        public async void ConnectRetriesOnError()
        {
            int invokationCount = 0;
            var wh = new ManualResetEventSlim();
            var redisConnection = GetMockRedisConnection();

            var tcs = new TaskCompletionSource<object>();
            tcs.TrySetCanceled();

            redisConnection.Setup(m => m.ConnectAsync(It.IsAny<string>(), It.IsAny<TraceSource>())).Returns<string, TraceSource>((connectionString, trace) =>
            {
                if (++invokationCount == 2)
                {
                    wh.Set();
                    return Task.FromResult(0);
                }
                else
                {
                    return tcs.Task;
                }
            });

            var redisMessageBus = new RedisMessageBus(GetDependencyResolver(), new RedisScaleoutConfiguration(String.Empty, String.Empty),
            redisConnection.Object, false);

            await redisMessageBus.ConnectWithRetry();

            Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
            Assert.Equal(RedisMessageBus.State.Connected, redisMessageBus.ConnectionState);
        }
开发者ID:kietnha,项目名称:SignalR,代码行数:30,代码来源:RedisMessageBusFacts.cs

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

示例15: Ctor_ThrowsAnException_IfLockCanNotBeGranted

        public void Ctor_ThrowsAnException_IfLockCanNotBeGranted()
        {
            var releaseLock = new ManualResetEventSlim(false);
            var lockAcquired = new ManualResetEventSlim(false);

            var thread = new Thread(
                () => UseConnection(connection1 =>
                {
                    var storage = CreateStorage(connection1);
                    using (new SqlServerDistributedLock(storage, "exclusive", _timeout))
                    {
                        lockAcquired.Set();
                        releaseLock.Wait();
                    }
                }));
            thread.Start();

            lockAcquired.Wait();

            UseConnection(connection2 =>
            {
                var storage = CreateStorage(connection2);
                Assert.Throws<DistributedLockTimeoutException>(
                    () =>
                    {
                        using (new SqlServerDistributedLock(storage, "exclusive", _timeout))
                        {
                        }
                    });
            });

            releaseLock.Set();
            thread.Join();
        }
开发者ID:harriyott,项目名称:Hangfire,代码行数:34,代码来源:SqlServerDistributedLockFacts.cs


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