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


C# AutoResetEvent.Set方法代码示例

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


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

示例1: Main

        static int Main(string[] args)
        {
            var finishedProcessing = new AutoResetEvent(false);
            int returnCode = 0;

            var index = new IndexFiles();
            index.Out_Statistics += stats =>
                {
                    System.Console.WriteLine("Successfully indexed {0} words.", stats.WordCount);
                    returnCode = 0;
                    finishedProcessing.Set();
                };

            index.Out_ValidationError += err =>
                {
                    System.Console.WriteLine("*** Aborted indexing! Validation error: {0}", err);
                    returnCode = 1;
                    finishedProcessing.Set();
                };

            index.Out_UnhandledException += ex =>
                {
                    System.Console.WriteLine("*** Aborted indexing! Unexpected exception: {0}. See log for details.", ex.Message);
                    returnCode = 99;
                    finishedProcessing.Set();
                };

            System.Console.WriteLine("Indexing files in {0} [Thread {1}]", args[0], Thread.CurrentThread.GetHashCode());

            index.Index(args[0], args[1]);

            finishedProcessing.WaitOne();
            return returnCode;
        }
开发者ID:yovannyr,项目名称:architectsnapkinebc,代码行数:34,代码来源:Program.cs

示例2: should_consume_with_valid_consumer

            public void should_consume_with_valid_consumer()
            {
                int result = 0;
                var waitHandle = new AutoResetEvent(false);

                IBus producer = this.StartBus(
                    "producer",
                    cfg =>
                        {
                            Func<IRouteResolverBuilder, IRouteResolver> routeResolverBuilder = b => b.Topology.Declare(Exchange.Named("multi.exchange"));

                            cfg.Route("boo.request")
                                .ConfiguredWith(routeResolverBuilder);
                            cfg.Route("foo.request")
                                .ConfiguredWith(routeResolverBuilder);
                        });

                this.StartBus(
                    "consumer",
                    cfg =>
                        {
                            Func<ISubscriptionEndpointBuilder, ISubscriptionEndpoint> subscriptionBuilder = b =>
                                {
                                    Exchange e = b.Topology.Declare(Exchange.Named("multi.exchange"));
                                    Queue q = b.Topology.Declare(Queue.Named("multi.queue"));
                                    b.Topology.Bind(e, q);

                                    return new SubscriptionEndpoint(q, e);
                                };

                            cfg.On<BooMessage>("boo.request")
                                .ReactWith(
                                    (m, ctx) =>
                                        {
                                            result = m.Num;
                                            waitHandle.Set();
                                        })
                                .WithEndpoint(subscriptionBuilder);
                            cfg.On<FooMessage>("foo.request")
                                .ReactWith(
                                    (m, ctx) =>
                                        {
                                            result = m.Num * 2;
                                            waitHandle.Set();
                                        })
                                .WithEndpoint(subscriptionBuilder);
                        });

                producer.Emit("boo.request", new BooMessage(13));

                waitHandle.WaitOne(5.Seconds()).Should().BeTrue();

                result.Should().Be(13);

                producer.Emit("foo.request", new FooMessage(13));

                waitHandle.WaitOne(5.Seconds()).Should().BeTrue();

                result.Should().Be(26);
            }
开发者ID:ehramovich,项目名称:Contour,代码行数:60,代码来源:BasicPublishingSpecs.cs

示例3: TestDisconnect

        public void TestDisconnect()
        {
            var ev = new AutoResetEvent(false);
            var succeeded = false;
            var communicationLayer = new SocketConnection();
            communicationLayer.ConnectionSucceeded += () =>
            {
                succeeded = true;
                ev.Set();
            };
            communicationLayer.ErrorOccurred += (msg) =>
            {
                succeeded = false;
                ev.Set();
            };
            communicationLayer.StartConnect("localhost", 80);
            ev.WaitOne(5000);
            Assert.IsTrue(succeeded);

            var disconnectEv = new AutoResetEvent(false);
            communicationLayer.ServerDisconnected += () => disconnectEv.Set();
            communicationLayer.StartDisconnect();

            disconnectEv.WaitOne(5000);
            Assert.IsFalse(communicationLayer.Connected);
        }
开发者ID:Mitch-Constantine,项目名称:CometGateway,代码行数:26,代码来源:SocketConnectionTest.cs

示例4: Intercept

        public void Intercept(IInvocation invocation)
        {
            var circuitName = invocation.Method.DeclaringType.Name;

            // Setup a new circuit if needed
            if (!_circuits.ContainsKey(circuitName))
            {
                _circuits.Add(circuitName, new Circuit());
            }

            var circuit = _circuits[circuitName];

            // If the circuit breaker has been tripped, fail fast 
            if (circuit.IsOffline)
            {
                throw new Exception("This service is misbehaving and has been taken offline");
            }

            // The circuit breaker hasn't been tripped - allow it
            try
            {
                var autoReset = new AutoResetEvent(false);
                var exception = null as Exception;
                ThreadPool.QueueUserWorkItem(
                    thread =>
                        {
                            try
                            {

                                invocation.Proceed();
                                autoReset.Set();
                            }
                            catch (Exception innerException)
                            {
                                exception = innerException;
                                autoReset.Set();
                            }
                        });
                var success = autoReset.WaitOne(3000);
                if (!success)
                {
                    // It timed out
                    circuit.RecordTimeout();
                    throw new TimeoutException("The call timed out");
                }
                if (exception != null)
                {
                    throw exception;
                }
            }
            catch (TimeoutException) 
            {
                throw;
            }
            catch (Exception ex)
            {
                circuit.RecordException(ex);
                throw;
            }
        }
开发者ID:PaulStovell,项目名称:presentations,代码行数:60,代码来源:CircuitBreakerInterceptor.cs

示例5: Test_QueueUrl_AlreadyQueued1

		public async Task Test_QueueUrl_AlreadyQueued1 ()
		{
			var bus = new InProcessBus ();
			var repo = new DownloadRepositoryMock ();
			var manager = new DownloadManager.iOS.DownloadManager (bus, repo);
			var wait1 = new AutoResetEvent (false);

			bool alreadyQueued = false;
			bool checkFreeSlot = false;

			bus.Subscribe<AlreadyQueued> (p => {
				alreadyQueued = true;
				wait1.Set();
			});

			bus.Subscribe<CheckFreeSlot> (p => {
				checkFreeSlot = true;
				wait1.Set();
			});

			repo.Insert(new Download {
				Url = "http://url.com/download/file.zip"
			});

			manager.QueueUrl (new QueueUrl {
				Url = "http://url.com/download/file.zip"
			});

			wait1.WaitOne ();

			Assert.AreEqual (false, checkFreeSlot);
			Assert.AreEqual (true, alreadyQueued);

		}
开发者ID:lduchosal,项目名称:DownloadManager.Xamarin,代码行数:34,代码来源:DownloadManagerTest+(copier).cs

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

示例7: GetRequestTime

        /// <summary>
        /// Считает время ожидания ответа на запрос к http серверу
        /// </summary>
        /// <param name="address">Url адрес</param>
        /// <param name="maxRequestTime">Максимальное время ожидания ответа. -1 для бесконечного времени ожидания.</param>
        /// <returns>Время запроса в мс</returns>

        internal static int GetRequestTime(string address, RequestParams requestParams, int maxRequestTime, out Exception outEx)
        {
            int result = -1;
            Exception innerEx = null;
            using (var request = new HttpRequest())
            {
                request.UserAgent = HttpHelper.ChromeUserAgent();
                EventWaitHandle wh = new AutoResetEvent(false);
                var requestThread = new Thread(() =>
                {
                    var watch = new Stopwatch();
                    watch.Start();
                    try
                    {
                        string resultPage = request.Get(address, requestParams).ToString();
                    }
                    catch (Exception ex) { innerEx = ex; }
                    result = Convert.ToInt32(watch.ElapsedMilliseconds);
                    watch.Reset();
                    wh.Set();
                });
                requestThread.Start();
                var stoptimer = new System.Threading.Timer((Object state) =>
                {
                    requestThread.Abort();
                    wh.Set();
                }, null, maxRequestTime, Timeout.Infinite);
                wh.WaitOne();

                stoptimer.Dispose();
            }
            outEx = innerEx;
            return result;
        }
开发者ID:CoffeeNova,项目名称:bfbalance,代码行数:41,代码来源:ByflyTools.cs

示例8: RequestGeneratorRetrieveTest

        public void RequestGeneratorRetrieveTest()
        {
            IRequestGenerator requestGenerator = new WebRequestGenerator();
            const string TestUri = "http://beta-api.etsy.com/v1/listings/featured/front?offset=0&limit=10&detail_level=low&api_key=" +
                NetsyData.EtsyApiKey;

            string resultString = string.Empty;
            Exception ex = null;

            using (AutoResetEvent waitEvent = new AutoResetEvent(false))
            {
                Action<string> successAction = s =>
                     {
                        resultString = s;
                        waitEvent.Set();
                     };

                Action<Exception> errorAction = e =>
                    {
                        ex = e;
                        waitEvent.Set();
                    };

                requestGenerator.StartRequest(new Uri(TestUri), successAction, errorAction);
                bool signalled = waitEvent.WaitOne(Constants.WaitTimeout);

                Assert.IsTrue(signalled);
                Assert.IsFalse(string.IsNullOrEmpty(resultString));
                Assert.IsNull(ex);
            }
        }
开发者ID:AnthonySteele,项目名称:Netsy,代码行数:31,代码来源:WebRequestGeneratorTest.cs

示例9: Build

        public static ITileSource Build(
            string urlToTileMapXml, 
            bool overrideTmsUrlWithUrlToTileMapXml)
        {
            var webRequest = (HttpWebRequest) WebRequest.Create(urlToTileMapXml);
            var waitHandle = new AutoResetEvent(false);
            ITileSource tileSource = null;
            Exception error = null;

            var state = new object[]
            {
                new Action<Exception>(ex =>
                {
                    error = ex;
                    waitHandle.Set();
                }),
                new Action<ITileSource>(ts =>
                {
                    tileSource = ts;
                    waitHandle.Set();
                }),
                webRequest,
                urlToTileMapXml,
                overrideTmsUrlWithUrlToTileMapXml
            };
            webRequest.BeginGetResponse(LoadTmsLayer, state);

            waitHandle.WaitOne();
            if (error != null) throw error;
            return tileSource;
        }
开发者ID:jdeksup,项目名称:Mapsui.Net4,代码行数:31,代码来源:TmsTileSourceBuilder.cs

示例10: Test_Add_and_Retrieve

        public void Test_Add_and_Retrieve()
        {
            var testBooking = CreateTestBooking();

            Booking actual = null;
            var waiter = new AutoResetEvent(false);
            _client.AddBookingAsync(testBooking, booking =>
                {
                    actual = booking;
                    waiter.Set();
                });

            Assert.IsTrue(waiter.WaitOne(1000), "Timeout waiting for WCF asynk result");
            Assert.AreNotSame(testBooking, actual, "WCF trip over the wire should have created a new object through serialisation");

            //Test that Get the saved booking works over WCF
            IEnumerable<Booking> actualBookings = null;
            waiter.Reset();
            _client.GetBookingsAsync(DateTime.Now, bookings =>
            {
                actualBookings = bookings;
                waiter.Set();
            });

            Assert.IsTrue(waiter.WaitOne(1000), "Timeout waiting for WCF asynk result");

            var retrievedBooking = actualBookings.FirstOrDefault();
            Assert.IsNotNull(retrievedBooking, "Bookings should contain created booking");
            Assert.AreEqual(testBooking.Id, retrievedBooking.Id, "Id is not persisted corectly");
            Assert.AreEqual(testBooking.ClientName, retrievedBooking.ClientName, "ClientName is not persisted corectly");
            Assert.AreEqual(testBooking.Duration, retrievedBooking.Duration, "Duration is not persisted corectly");
            Assert.AreEqual(testBooking.Slot, retrievedBooking.Slot, "Slot is not persisted corectly");
        }
开发者ID:stefanidi,项目名称:NineITBookingAppByRomanStefanidi,代码行数:33,代码来源:WcfTests.cs

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

示例12: Main

        static void Main(string[] args)
        {
            m_WebSockets = new WebSocket[1000];

            var autoEventReset = new AutoResetEvent(false);

            for(var i = 0; i < m_WebSockets.Length; i++)
            {
                var websocket = new WebSocket("ws://localhost:2011/");
                websocket.Opened += (s, e) =>
                    {
                        autoEventReset.Set();
                    };
                websocket.Error +=  (s, e) =>
                    {
                        Console.WriteLine(e.Exception.Message);
                        autoEventReset.Set();
                    };

                websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);
                websocket.Open();
                autoEventReset.WaitOne();

                m_WebSockets[i] = websocket;

                Console.WriteLine(i);
            }

            Console.WriteLine("All connected");
            Console.ReadLine();
        }
开发者ID:2594636985,项目名称:SuperWebSocket,代码行数:31,代码来源:Program.cs

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

示例14: DispatchActionToMainWindow

        public void DispatchActionToMainWindow(Action message)
        {
            bool loaded = false;

            if (Application.Current.Dispatcher.HasShutdownStarted)
                message();

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (Application.Current.MainWindow != null)
                {
                    loaded = Application.Current.MainWindow.IsLoaded;
                    return;
                }
                loaded = false;
            }));
            if (!loaded)
            {
                var handle = new AutoResetEvent(false);
                EventHandler set = delegate { handle.Set(); };
                Application.Current.Dispatcher.Invoke(
                    new Action(() =>
                    {
                        if (Application.Current.MainWindow != null)
                            Application.Current.MainWindow.Loaded += (sender, args) => handle.Set();
                        else
                            Application.Current.Activated += set;
                    }));

                handle.WaitOne();
                Application.Current.Activated -= set;
            }

            Application.Current.Dispatcher.Invoke(message);
        }
开发者ID:JPVenson,项目名称:Shell_Temp,代码行数:35,代码来源:ErrorWindowService.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.Set方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。