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


C# AutoResetEvent.WaitOne方法代码示例

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


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

示例1: TestDelete

 public void TestDelete()
 {
     FileInfo file = new FileInfo(@"d:\X16-42552VS2010UltimTrial1.txt");
     AutoResetEvent are = new AutoResetEvent(false);
     string key = null;
     HttpCommunicate.Upload(file, (result, warning) =>
     {
         Console.WriteLine("result:" + result);
         key = result + "";
         are.Set();
     }, error =>
     {
         Console.WriteLine("error:" + error);
         are.Set();
     });
     are.WaitOne();
     are.Reset();
     FileDeletePackage package = new FileDeletePackage();
     package.key = key;
     HttpCommunicate.Request(package, (result, warning) =>
     {
         Console.WriteLine("file:" + result);
         are.Set();
     }, error =>
     {
         Console.WriteLine("error:" + error);
         are.Set();
     });
     are.WaitOne();
 }
开发者ID:wangjianglin,项目名称:dotnet-core,代码行数:30,代码来源:FileTest.cs

示例2: CurrentIsVisibleAccrossThreads

        public void CurrentIsVisibleAccrossThreads()
        {
            var sqlCharacters = new TestSqlCharacters();

            SqlCharacters actual = null;
            var handle = new AutoResetEvent(false);

            var thread1 = new Thread(() =>
            {
                SqlCharacters.Current = sqlCharacters;
                handle.Set();
            });

            var thread2 = new Thread(() =>
            {
                actual = SqlCharacters.Current;
                handle.Set();
            });

            thread1.Start();
            handle.WaitOne();

            thread2.Start();
            handle.WaitOne();

            thread1.Abort();
            thread2.Abort();

            Assert.Same(sqlCharacters, actual);
        }
开发者ID:TrevorPilley,项目名称:MicroLite,代码行数:30,代码来源:SqlCharactersTests.cs

示例3: ClearMarkedPosts

        public static bool ClearMarkedPosts(ThreadMetadata thread, int timeout = CoreConstants.DEFAULT_TIMEOUT_IN_MILLISECONDS)
        {
            // create request
            HttpWebRequest request = AwfulWebRequest.CreateFormDataPostRequest(
                "http://forums.somethingawful.com/showthread.php",
                "application/x-www-form-urlencoded");

            // begin request stream creation and wait...
            var signal = new AutoResetEvent(false);
            var result = request.BeginGetRequestStream(callback =>
                SendClearMarkedPostRequest(callback, signal, thread),
                request);

            signal.WaitOne();

            // begin response stream and wait...
            request = result.AsyncState as HttpWebRequest;
            result = request.BeginGetResponse(callback => { signal.Set(); }, request);
            signal.WaitOne(timeout);

            if (!result.IsCompleted)
                throw new TimeoutException();

            // process the response and return status
            bool success = ProcessClearMarkedPostResponse(result);
            return success;
        }
开发者ID:bootlegrobot,项目名称:awful2,代码行数:27,代码来源:ThreadService.cs

示例4: Test_SendToWrongPort

        public void Test_SendToWrongPort()
        {
            IPEndPoint ep1 = new IPEndPoint (IPAddress.Parse ("10.0.0.1"), 10000);
            IPEndPoint ep2 = new IPEndPoint (IPAddress.Parse ("10.0.0.2"), 10000);

            VirtualNetwork network = new VirtualNetwork (LatencyTypes.Constant (20), 5, PacketLossType.Lossless (), 2);
            byte[] msg = new byte[]{0, 1, 2, 3};
            try {
                using (AutoResetEvent done = new AutoResetEvent (false))
                using (VirtualDatagramEventSocket sock1 = new VirtualDatagramEventSocket (network, ep1.Address))
                using (VirtualDatagramEventSocket sock2 = new VirtualDatagramEventSocket (network, ep2.Address)) {
                    sock1.Bind (new IPEndPoint (IPAddress.Any, ep1.Port));
                    sock2.Bind (new IPEndPoint (IPAddress.Any, ep2.Port));
                    sock1.Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) {
                        done.Set ();
                    });
                    sock2.Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) {
                        done.Set ();
                    });
                    sock1.SendTo (msg, new IPEndPoint (ep2.Address, ep2.Port + 1));
                    Assert.IsFalse (done.WaitOne (500));
                    sock2.SendTo (msg, ep1);
                    Assert.IsTrue (done.WaitOne ());
                }
            } finally {
                network.Close ();
            }
        }
开发者ID:kazuki,项目名称:p2pncs,代码行数:28,代码来源:VirtualDatagramEventSocketTest.cs

示例5: Main

        static void Main(string[] args)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);

            // create the workflow app and add handlers for the Idle and Completed actions
            WorkflowApplication app = new WorkflowApplication(new Sequence1());
            app.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                syncEvent.Set();
            };
            app.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                syncEvent.Set();
            };

            // start the application
            app.Run();
            syncEvent.WaitOne();

            // read some text from the console and resume the readText bookmark (created in the first WaitForInput activity)
            string text = Console.ReadLine();
            app.ResumeBookmark("readText", text);
            syncEvent.WaitOne();

            // read some text from the console, convert it to number, and resume the readNumber bookmark (created in the second WaitForInput activity)
            int number = ReadNumberFromConsole();
            app.ResumeBookmark("readNumber", number);
            syncEvent.WaitOne();

            Console.WriteLine("");
            Console.WriteLine("Press [ENTER] to exit...");
            Console.ReadLine();
        }
开发者ID:tian1ll1,项目名称:WPF_Examples,代码行数:33,代码来源:Program.cs

示例6: Do_Timeout

        public void Do_Timeout()
        {
            var sw = Stopwatch.StartNew();
            const int ms = 100;
            var i = 0;
            var ellapsed = 0L;
            var wait = new AutoResetEvent(false);
            Do.Timeout(() =>
                           {
                               ellapsed = sw.ElapsedMilliseconds;
                               i++;
                               wait.Set();
                           }, ms);
            if (wait.WaitOne(ms * 3))
            {
                Assert.AreEqual(1, i);
                Assert.IsTrue(ellapsed > ms * .9);
            } else
            {
                Assert.Fail("callback not executed.");
            }

            sw.Restart();
            var killswitch = Do.Timeout(() => { wait.Set(); }, ms * 2);
            killswitch.Kill();
            ellapsed = sw.ElapsedMilliseconds;
            Assert.IsTrue(ellapsed < ms * 2);
            if (wait.WaitOne(ms * 4))
            {
                Assert.Fail("Unable to stop timeout.");
            }
        }
开发者ID:blesh,项目名称:ALE,代码行数:32,代码来源:Do_Tests.cs

示例7: Main

        static void Main(string[] args)
        {
            // Create an event to signal the timeout count threshold in the timer callback.
            AutoResetEvent autoEvent = new AutoResetEvent(false);

            StatusChecker statusChecker = new StatusChecker(10);

            // Create an inferred delegate that invokes methods for the timer.
            TimerCallback tcb = statusChecker.CheckStatus;

            // Create a timer that signals the delegate to invoke CheckStatus after one second, 
            // and every 1/4 second thereafter.
            Console.WriteLine("{0} Creating timer.\n", DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);

            // When autoEvent signals, change the period to every  1/2 second.
            autoEvent.WaitOne(5000, false);
            stateTimer.Change(0, 500);
            Console.WriteLine("\nChanging period.\n");

            // When autoEvent signals the second time, dispose of the timer.
            autoEvent.WaitOne(5000, false);
            stateTimer.Dispose();
            Console.WriteLine("\nDestroying timer.");
        }
开发者ID:JeffESchmitz,项目名称:Console.Examples,代码行数:25,代码来源:Program.cs

示例8: CreateClient

        /// <summary>
        /// Create a Pusher Client, and subscribes a user
        /// </summary>
        /// <param name="pusherServer">Server to connect to</param>
        /// <param name="reset">The AutoReset to control the subscription by the client</param>
        /// <param name="channelName">The name of the channel to subscribe to</param>
        /// <returns>A subscribed client</returns>
        public static PusherClient.Pusher CreateClient(Pusher pusherServer, AutoResetEvent reset, string channelName)
        {
            PusherClient.Pusher pusherClient =
                new PusherClient.Pusher(Config.AppKey, new PusherClient.PusherOptions()
                {
                    Authorizer = new InMemoryAuthorizer(
                        pusherServer,
                        new PresenceChannelData()
                        {
                            user_id = "Mr Pusher",
                            user_info = new { twitter_id = "@pusher" }
                        })
                });

            pusherClient.Connected += delegate { reset.Set(); };

            pusherClient.Connect();

            reset.WaitOne(TimeSpan.FromSeconds(5));

            var channel = pusherClient.Subscribe(channelName);

            channel.Subscribed += delegate { reset.Set(); };

            reset.WaitOne(TimeSpan.FromSeconds(5));

            return pusherClient;
        }
开发者ID:pusher,项目名称:pusher-http-dotnet,代码行数:35,代码来源:ClientServerFactory.cs

示例9: Success

        public void Success()
        {
            AutoResetEvent completed = new AutoResetEvent(false);

            if (Socket.OSSupportsIPv4)
            {
                int port, port1;
                using (SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port))
                using (SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port1))
                {
                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.Completed += OnCompleted;
                    args.UserToken = completed;
                    args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port);
                    args.DisconnectReuseSocket = true;

                    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    Assert.True(client.ConnectAsync(args));
                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");
                    Assert.Equal<SocketError>(SocketError.Success, args.SocketError);

                    client.Disconnect(true);

                    args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port1);

                    Assert.True(client.ConnectAsync(args));
                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");
                    Assert.Equal<SocketError>(SocketError.Success, args.SocketError);

                    client.Dispose();
                }
            }
        }
开发者ID:shrutigarg,项目名称:corefx,代码行数:34,代码来源:Disconnect.cs

示例10: DisconnectAsync_Success

        public void DisconnectAsync_Success()
        {
            AutoResetEvent completed = new AutoResetEvent(false);

            IPEndPoint loopback = new IPEndPoint(IPAddress.Loopback, 0);
            using (var server1 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback))
            using (var server2 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback))
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += OnCompleted;
                args.UserToken = completed;
                args.RemoteEndPoint = server1.EndPoint;
                args.DisconnectReuseSocket = true;

                using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    Assert.True(client.ConnectAsync(args));
                    completed.WaitOne();
                    Assert.Equal(SocketError.Success, args.SocketError);

                    Assert.True(client.DisconnectAsync(args));
                    completed.WaitOne();
                    Assert.Equal(SocketError.Success, args.SocketError);

                    args.RemoteEndPoint = server2.EndPoint;

                    Assert.True(client.ConnectAsync(args));
                    completed.WaitOne();
                    Assert.Equal(SocketError.Success, args.SocketError);
                }
            }
        }
开发者ID:Corillian,项目名称:corefx,代码行数:32,代码来源:DisconnectTest.cs

示例11: describe_custom_gossip_message_factory_creating_different_message_types

        public void describe_custom_gossip_message_factory_creating_different_message_types()
        {
            var clusterConfig = new GossipClusterConfig { ClusterKey = Encoding.UTF8.GetBytes("ClusterKey") };
            var nodeConfig1 = new GossipNodeConfig(new IPEndPoint(IPAddress.Loopback, NodePort1));
            var nodeConfig2 = new GossipNodeConfig(new IPEndPoint(IPAddress.Loopback, NodePort2));
            var message1 = new GossipMessage1();
            var message2 = new GossipMessage2();
            GossipMessageFactory.CreateMessage += CreateMessage;

            using (var node1 = new GossipNode(nodeConfig1, clusterConfig))
            using (var node2 = new GossipNode(nodeConfig2, clusterConfig))
            {
                var received = new AutoResetEvent(false);
                GossipMessage receivedMsg = null;
                node1.OnMessageReceived += (node, conn, msg) =>
                                               {
                                                   receivedMsg = msg;
                                                   received.Set();
                                               };

                node1.StartListening();
                node2.StartListening();

                node1.Cluster.Join(new GossipClusterMember(nodeConfig1.NodeId, nodeConfig2, node2.Authenticator));
                node2.Cluster.Join(new GossipClusterMember(nodeConfig2.NodeId, nodeConfig1, node1.Authenticator));

                node2.Cluster.BroadcastMessage(message1);
                if (!received.WaitOne(Timeout)) Assert.Fail();
                Assert.IsInstanceOf<GossipMessage1>(receivedMsg);

                node2.Cluster.BroadcastMessage(message2);
                if (!received.WaitOne(Timeout)) Assert.Fail();
                Assert.IsInstanceOf<GossipMessage2>(receivedMsg);
            }
        }
开发者ID:hoangvv1409,项目名称:codebase,代码行数:35,代码来源:GossipMessageFactoryTests.cs

示例12: Should_Receive_Many_Envelopes_When_Filter_Returns_True

        public void Should_Receive_Many_Envelopes_When_Filter_Returns_True()
        {
            InMemoryEnvelopeBus bus = new InMemoryEnvelopeBus();
            AutoResetEvent waitHandle = new AutoResetEvent(false);

            Envelope env = new Envelope();
            env.Payload = Encoding.UTF8.GetBytes("Test");

            Mock<IRegistration> reg = _mocker.Create<IRegistration>();
            reg.Setup(r => r.Filter).Returns(new Predicate<Envelope>(e => true));
            reg.Setup(r => r.Handle(env)).Callback(() => waitHandle.Set());

            bus.Register(reg.Object);

            bus.Send(env);
            waitHandle.WaitOne(5000);

            bus.Send(env);
            waitHandle.WaitOne(5000);

            bus.Send(env);
            waitHandle.WaitOne(5000);

            bus.Send(env);
            waitHandle.WaitOne(5000);

            bus.Send(env);
            waitHandle.WaitOne(5000);

            reg.Verify(r => r.Handle(env), Times.Exactly(5));
        }
开发者ID:berico-tpinney,项目名称:AMP,代码行数:31,代码来源:InMemoryEnvBusTests.cs

示例13: MessageAfterExceptionTest

        public void MessageAfterExceptionTest()
        {
            Exception e = null;
            AutoResetEvent even = new AutoResetEvent(false);
            int y = 0;
            var a = new Arbitr<Message, NOPMessage>(
                (z) =>
                {
                    y = 1 / z.x;
                    even.Set();
                },
                (z) =>
                {
                    e = z;
                    even.Set();
                });

            a.Send(new Message() { x = 0 });
            bool completed = even.WaitOne(500);

            Assert.IsTrue(completed);
            Assert.IsNotNull(e);
            Assert.AreEqual(y, 0);

            e = null;
            a.Send(new Message() { x = 1 });
            completed = even.WaitOne(500);

            Assert.IsTrue(completed);
            Assert.IsNull(e);
            Assert.AreEqual(y, 1);
        }
开发者ID:lebaon,项目名称:AEF,代码行数:32,代码来源:StaticTests.cs

示例14: AsyncStorageModule_InvalidKeyValue_Method

        public void AsyncStorageModule_InvalidKeyValue_Method()
        {
            var module = new AsyncStorageModule();
            var waitHandle = new AutoResetEvent(false);

            var error = default(JObject);
            var result = default(JArray);
            var callback = new MockCallback(res =>
            {
                error = res.Length > 0 ? (JObject)res[0] : null;
                result = res.Length > 1 ? (JArray)res[1] : null;
                waitHandle.Set();
            });

            var array = new[]
            {
                new[] { "5", "5", "5" },
            };

            module.clear(callback);
            Assert.IsTrue(waitHandle.WaitOne());
            Assert.IsNull(error);
            Assert.IsNull(result);

            module.multiSet(array, callback);
            Assert.IsTrue(waitHandle.WaitOne());
            Assert.AreEqual(error["message"], "Invalid Value");
            Assert.IsNull(result);
        }
开发者ID:chukcha-wtf,项目名称:react-native-windows,代码行数:29,代码来源:AsyncStorageModuleTests.cs

示例15: when_receiving_message_then_can_send_new_message

        public void when_receiving_message_then_can_send_new_message()
        {
            var secondReceiver = new TestableMessageReceiver(this.connectionFactory);

            this.sender.Send(new Message("message1"));

            var waitEvent = new AutoResetEvent(false);
            string receiver1Message = null;
            string receiver2Message = null;

            this.receiver.MessageReceived += (s, e) =>
            {
                waitEvent.Set();
                receiver1Message = e.Message.Body;
                waitEvent.WaitOne();
            };
            secondReceiver.MessageReceived += (s, e) =>
            {
                receiver2Message = e.Message.Body;
            };

            ThreadPool.QueueUserWorkItem(_ => { this.receiver.ReceiveMessage(); });

            Assert.IsTrue(waitEvent.WaitOne(TimeSpan.FromSeconds(10)));
            this.sender.Send(new Message("message2"));
            secondReceiver.ReceiveMessage();
            waitEvent.Set();

            Assert.IsTrue("message1" == receiver1Message);
            Assert.IsTrue("message2" == receiver2Message);
        }
开发者ID:hoangvv1409,项目名称:codebase,代码行数:31,代码来源:MessageReceiverFixture.cs


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