當前位置: 首頁>>代碼示例>>C#>>正文


C# ManualResetEvent.Reset方法代碼示例

本文整理匯總了C#中System.Threading.ManualResetEvent.Reset方法的典型用法代碼示例。如果您正苦於以下問題:C# ManualResetEvent.Reset方法的具體用法?C# ManualResetEvent.Reset怎麽用?C# ManualResetEvent.Reset使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.Threading.ManualResetEvent的用法示例。


在下文中一共展示了ManualResetEvent.Reset方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: CallbackInvokedMultipleTimes

        public void CallbackInvokedMultipleTimes()
        {
            var reRegisterForFinalize = true;
            var callbackInvoked = new ManualResetEvent(false);
            GcNotification.Register(state =>
            {
                callbackInvoked.Set();
                return reRegisterForFinalize;
            }, null);

            GcCollectAndWait();
            Assert.True(callbackInvoked.WaitOne(0));

            callbackInvoked.Reset();
            reRegisterForFinalize = false;

            GcCollectAndWait();
            Assert.True(callbackInvoked.WaitOne(0));

            callbackInvoked.Reset();

            // No callback expected the 3rd time
            GcCollectAndWait();
            Assert.False(callbackInvoked.WaitOne(0));
        }
開發者ID:andyshao,項目名稱:Caching,代碼行數:25,代碼來源:GcNotificationTests.cs

示例2: CallbackInvokedMultipleTimes

        public void CallbackInvokedMultipleTimes()
        {
            int callbackCount = 0;
            var callbackInvoked = new ManualResetEvent(false);
            GcNotification.Register(state =>
            {
                callbackCount++;
                callbackInvoked.Set();
                if (callbackCount < 2)
                {
                    return true;
                }
                return false;
            }, null);

            GC.Collect(2, GCCollectionMode.Forced, blocking: true);
            Assert.True(callbackInvoked.WaitOne(100));
            Assert.Equal(1, callbackCount);

            callbackInvoked.Reset();

            GC.Collect(2, GCCollectionMode.Forced, blocking: true);
            Assert.True(callbackInvoked.WaitOne(100));
            Assert.Equal(2, callbackCount);

            callbackInvoked.Reset();

            // No callback expected the 3rd time
            GC.Collect(2, GCCollectionMode.Forced, blocking: true);
            Assert.False(callbackInvoked.WaitOne(100));
            Assert.Equal(2, callbackCount);
        }
開發者ID:vagelious,項目名稱:ergotaxionion,代碼行數:32,代碼來源:GcNotificationTests.cs

示例3: Run

        public static void Run()
        {
            // ExStart:SupportIMAPIdleCommand
            // Connect and log in to IMAP 
            ImapClient client = new ImapClient("imap.domain.com", "username", "password");

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            ImapMonitoringEventArgs eventArgs = null;
            client.StartMonitoring(delegate(object sender, ImapMonitoringEventArgs e)
            {
                eventArgs = e;
                manualResetEvent.Set();
            });
            Thread.Sleep(2000);
            SmtpClient smtpClient = new SmtpClient("exchange.aspose.com", "username", "password");
            smtpClient.Send(new MailMessage("[email protected]", "[email protected]", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(10000);
            manualResetEvent.Reset();
            Console.WriteLine(eventArgs.NewMessages.Length);
            Console.WriteLine(eventArgs.DeletedMessages.Length);
            client.StopMonitoring("Inbox");
            smtpClient.Send(new MailMessage("[email protected]", "[email protected]", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(5000);
            // ExEnd:SupportIMAPIdleCommand
        }
開發者ID:aspose-email,項目名稱:Aspose.Email-for-.NET,代碼行數:25,代碼來源:SupportIMAPIdleCommand.cs

示例4: TestAsyncGetTicket

        public void TestAsyncGetTicket()
        {
            BoxManager manager = new BoxManager(ApplicationKey, ServiceUrl, null);
            const int someValue = 78435;
            ManualResetEvent wait = new ManualResetEvent(false);
            bool callbackWasExecuted = false;

            OperationFinished<GetTicketResponse> response = resp =>
                                                                {
                                                                    Assert.IsNull(resp.Error);
                                                                    Assert.IsNotNull(resp.Ticket);
                                                                    Assert.IsInstanceOfType(typeof(int), resp.UserState);
                                                                    Assert.AreEqual(GetTicketStatus.Successful,  resp.Status);

                                                                    int userStatus = (int) resp.UserState;
                                                                    Assert.AreEqual(someValue, userStatus);

                                                                    callbackWasExecuted = true;

                                                                    wait.Reset();
                                                                };

            manager.GetTicket(response, someValue);

            wait.WaitOne(30000);

            Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out");
        }
開發者ID:CoderDennis,項目名稱:box-csharp-sdk,代碼行數:28,代碼來源:GetTicketTests.cs

示例5: Test

        public static void Test(ITransport t, IQueueStrategy strategy,
            Endpoint queueEndpoint, Action<Message> send, Func<MessageEnumerator>
            enumer)
        {
            Guid id = Guid.NewGuid();
            var serializer = new XmlMessageSerializer(new
                                                          DefaultReflection(), new DefaultKernel());

            var subscriptionStorage = new MsmqSubscriptionStorage(new
                                                                      DefaultReflection(),
                                                                  serializer,
                                                                  queueEndpoint.Uri,
                                                                  new
                                                                      EndpointRouter(),
                                                                  strategy);
            subscriptionStorage.Initialize();

            var wait = new ManualResetEvent(false);

            subscriptionStorage.SubscriptionChanged += () => wait.Set();

            t.AdministrativeMessageArrived +=
                subscriptionStorage.HandleAdministrativeMessage;

            Message msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     AddInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });
            send(msg);

            wait.WaitOne();

            msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     RemoveInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });

            wait.Reset();

            send(msg);

            wait.WaitOne();

            IEnumerable<Uri> uris = subscriptionStorage
                .GetSubscriptionsFor(typeof (TestMessage2));
            Assert.Equal(0, uris.Count());

            int count = 0;
            MessageEnumerator copy = enumer();
            while (copy.MoveNext()) count++;
            Assert.Equal(0, count);
        }
開發者ID:philiphoy,項目名稱:rhino-esb,代碼行數:60,代碼來源:FIeldProblem_Nick.cs

示例6: TestSuccesfulConnection

        public void TestSuccesfulConnection()
        {
            // setup
            Uri url = new Uri("http://test.com");
            CancellationTokenSource cts = new CancellationTokenSource();
            List<EventSourceState> states = new List<EventSourceState>();
            ServiceResponseMock response = new ServiceResponseMock(url, System.Net.HttpStatusCode.OK);
            WebRequesterFactoryMock factory = new WebRequesterFactoryMock(response);
            ManualResetEvent stateIsOpen = new ManualResetEvent(false);

            TestableEventSource es = new TestableEventSource(url, factory);
            es.StateChanged += (o, e) =>
            {
                states.Add(e.State);
                if (e.State == EventSourceState.OPEN)
                {
                    stateIsOpen.Set();
                    cts.Cancel();
                }
            };


            // act
            stateIsOpen.Reset();

            es.Start(cts.Token);

            stateIsOpen.WaitOne();

            // assert
            Assert.IsTrue(states.Count == 2);
            Assert.AreEqual(states[0], EventSourceState.CONNECTING);
            Assert.AreEqual(states[1], EventSourceState.OPEN);
        }
開發者ID:ChrisCross67,項目名稱:EventSource4Net,代碼行數:34,代碼來源:EventSourceTest.cs

示例7: StartListening

        public static void StartListening(int port = 11001)
        {
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = IPAddress.Parse(LocalSettings.ServerIP);
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
            _allDone = new ManualResetEvent(false);
            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);
                while (true)
                {
                    // Set the event to nonsignaled state.
                    _allDone.Reset();
                    // Start an asynchronous socket to listen for connections.
                    listener.BeginAccept(
                        AcceptCallback,
                        listener);
                    // Wait until a connection is made before continuing.
                    _allDone.WaitOne();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }
開發者ID:ryselis,項目名稱:viktoro_viktorina,代碼行數:35,代碼來源:MessagingServer.cs

示例8: FilteringTargetWrapperAsyncTest2

        public void FilteringTargetWrapperAsyncTest2()
        {
            var myMockCondition = new MyMockCondition(false);
            var myTarget = new MyAsyncTarget();
            var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
            wrapper.Initialize(CommonCfg);
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            var continuationHit = new ManualResetEvent(false);
            Action<Exception> continuation =
                ex =>
                {
                    lastException = ex;
                    continuationHit.Set();
                };

            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            continuationHit.WaitOne();
            Assert.IsNull(lastException);
            Assert.AreEqual(0, myTarget.WriteCount);
            Assert.AreEqual(1, myMockCondition.CallCount);

            continuationHit.Reset();
            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            continuationHit.WaitOne();
            Assert.IsNull(lastException);
            Assert.AreEqual(0, myTarget.WriteCount);
            Assert.AreEqual(2, myMockCondition.CallCount);
        }
開發者ID:ExM,項目名稱:NLog,代碼行數:30,代碼來源:FilteringTargetWrapperTests.cs

示例9: Start

        /// <summary>
        /// Start server and begin accepting clients
        /// </summary>
        public static void Start()
        {
            futureMoves = new Queue<FutureMove>();
            clientsPlaying = new List<Connection>();
            clientUpdate = new List<Connection>();
            clientAI = new List<Connection>();
            clientPlayers = new List<Connection>();
            clientsAll = new List<Connection>();
            updateTimer.Elapsed += new ElapsedEventHandler(UpdateTick);
            updateTimer.AutoReset = false;
            if (listener != null) listener.Stop();
            listener = TcpListener.Create(Program.port);
            listener.Start();
            allDone = new ManualResetEvent(false);
            try
            {
                while (true)
                {
                    allDone.Reset();
                    listener.BeginAcceptTcpClient(new AsyncCallback(AcceptTcpClient), listener);
                    allDone.WaitOne();
                }
            }
            catch (ThreadAbortException)
            {
                listener.Stop();
            }
        }
開發者ID:Xsichtik,項目名稱:Bomberman,代碼行數:31,代碼來源:Server.cs

示例10: TestAsyncGetAccountInfo_WhenUserIsNotLoggedIn_ThenStatusIsNotLoggedIn

        public void TestAsyncGetAccountInfo_WhenUserIsNotLoggedIn_ThenStatusIsNotLoggedIn()
        {
            const int status = 847587532;
            ManualResetEvent wait = new ManualResetEvent(false);
            bool callbackWasExecuted = false;

            OperationFinished<GetAccountInfoResponse> callback = resp =>
                                                                 	{
                                                                        Assert.AreEqual(GetAccountInfoStatus.NotLoggedIn, resp.Status);

                                                                        Assert.IsInstanceOf(typeof(int), resp.UserState);
                                                                        Assert.AreEqual(status, (int)resp.UserState);

                                                                        Assert.IsNull(resp.Error);
                                                                        Assert.IsNull(resp.User);

                                                                 		callbackWasExecuted = true;

                                                                 		wait.Reset();
                                                                 	};

            Context.Manager.Logout();

            Context.Manager.GetAccountInfo(callback, status);

            wait.WaitOne(30000);

            Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out");
        }
開發者ID:CoderDennis,項目名稱:box-csharp-sdk,代碼行數:29,代碼來源:GetAccountInfoTests.cs

示例11: TestAsyncGetAccountInfo

        public void TestAsyncGetAccountInfo()
        {
            const int status = 847587532;
            ManualResetEvent wait = new ManualResetEvent(false);
            bool callbackWasExecuted = false;

            OperationFinished<GetAccountInfoResponse> callback = resp =>
                                                                 	{
                                                                 		Assert.AreEqual(GetAccountInfoStatus.Successful, resp.Status);
                                                                 		Assert.IsNull(resp.Error);
                                                                 		Assert.IsInstanceOf(typeof(int), resp.UserState);
                                                                        Assert.AreEqual(status, (int)resp.UserState);

                                                                        Assert.IsNotNull(resp.User);

                                                                        Assert.AreEqual(Context.AuthenticatedUser.AccessID, resp.User.AccessID);
                                                                        Assert.AreEqual(Context.AuthenticatedUser.ID, resp.User.ID);
                                                                        Assert.AreEqual(Context.AuthenticatedUser.MaxUploadSize, resp.User.MaxUploadSize);
                                                                        Assert.AreEqual(Context.AuthenticatedUser.SpaceAmount, resp.User.SpaceAmount);
                                                                        Assert.AreEqual(Context.AuthenticatedUser.SpaceUsed, resp.User.SpaceUsed);

                                                                        StringAssert.IsMatch(Context.AuthenticatedUser.Email, resp.User.Email);
                                                                        StringAssert.IsMatch(Context.AuthenticatedUser.Login, resp.User.Login);

                                                                 		callbackWasExecuted = true;

                                                                 		wait.Reset();
                                                                 	};

            Context.Manager.GetAccountInfo(callback, status);

            wait.WaitOne(30000);

            Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out");
        }
開發者ID:CoderDennis,項目名稱:box-csharp-sdk,代碼行數:35,代碼來源:GetAccountInfoTests.cs

示例12: ContentLoader

        public ContentLoader(ContentLoaderProgressHandler progress)
        {
            LoaderQueue = new Queue<ContentLoaderItem>();
            ContinueLoaderThreadEvent = new ManualResetEvent(false);

            ContentLoaderThread = new Thread(delegate() {
                double itemIndex = 0;

                while (ContentLoaderThread.ThreadState != ThreadState.Aborted)
                {
                    if (LoaderQueue.Count > 0)
                    {                        
                        ContentLoaderItem item = LoaderQueue.Dequeue();
                        progress((++itemIndex) / (itemIndex + LoaderQueue.Count), item.Description);
                        item.Handler(item.Target);
                    }
                    else 
                    {
                        ContinueLoaderThreadEvent.WaitOne();
                    }
                    ContinueLoaderThreadEvent.Reset();
                }              
            });
            ContentLoaderThread.Start();
        }
開發者ID:vulsim,項目名稱:prism-client,代碼行數:25,代碼來源:ContentLoader.cs

示例13: MockPresenter

        public MockPresenter(Page.ePageType activePageType = Page.ePageType.AVItemCollectionGallery,
            string excludedTitles = "Popular,TV,V,W,Sports,ESPN,News",
            int imageWidth = IMAGE_WIDTH, int imageHeight = IMAGE_HEIGHT)
        {
            // start logging during mocking
            SetupLogging();

            _model = MediaServerModel.GetInstance();

            TitlesExcludedFromImageReplacement = excludedTitles;
            ImageWidth = imageWidth;
            ImageHeight = imageHeight;

            AVItemCollections = new ObservableCollection<UPnPCollection>();
            AVItems = new ObservableCollection<UPnPItem>();
            DetailItem = new ObservableCollection<UPnPItem>();
            Items = new ObservableCollection<AVItemBase>();

            _allDoneEvent = new ManualResetEvent(false);
            Logger.TraceInfo(MethodBase.GetCurrentMethod(), "MockPresenter _model: {0}", _model.Actions.ContentDirectory.Name);
            _model.Actions.ContentDirectory.NewDeviceFound += NewDeviceFound;
            _model.Actions.ContentDirectory.OnCreateControlPoint(null);
            _allDoneEvent.WaitOne();
            _allDoneEvent.Reset();
            WaitTimeBetweenGetImageInMilliseconds = 0;
            StartBackgroundThreadToGetImages();
            PropertyChanged += OnLocalPropertyChanged;

            // default to the showing a collection
            ActivePageType = activePageType;
            //ActivePageType = Page.ePageType.AVItemGallery;
            //ActivePageType = Page.ePageType.AVItemDetails;

            _allDoneEvent.WaitOne(TimeSpan.FromSeconds(15D));
        }
開發者ID:CarverLab,項目名稱:onCore.root,代碼行數:35,代碼來源:MockPresenter.cs

示例14: Main2

        public static void Main2(string[] args)
        {
            ManualResetEvent conn = new ManualResetEvent(false);
            int count = 0;
            Socket main = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint bindingPoint = new IPEndPoint(IPAddress.Any,6199);
            main.Bind(bindingPoint);
            main.Listen(10);
            Console.WriteLine("main socket status: Blocking:{0}, localIP:{1}", main.Blocking, main.LocalEndPoint.ToString());
            do
            {

                conn.Reset();
                lock (main)
                {
                    count++;
                }
                main.BeginAccept(AceptCallback, new stateObj { sck = main, ClientNo = count, conn = conn });
                Console.WriteLine("wait one : " + count);
                conn.WaitOne();
            }
            while (true);
            Console.ReadKey();
            main.Close(1000);
        }
開發者ID:knarf7112,項目名稱:SocketServer,代碼行數:25,代碼來源:Program2.cs

示例15: AcceptAsyncShouldUseAcceptSocketFromEventArgs

        public void AcceptAsyncShouldUseAcceptSocketFromEventArgs()
        {
            var readyEvent = new ManualResetEvent(false);
            var mainEvent = new ManualResetEvent(false);
            var listenSocket = new Socket(
                AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var serverSocket = new Socket(
                    AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Socket acceptedSocket = null;
            Exception ex = null;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                SocketAsyncEventArgs asyncEventArgs;
                try {
                    listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    listenSocket.Listen(1);

                    asyncEventArgs = new SocketAsyncEventArgs {AcceptSocket = serverSocket};
                    asyncEventArgs.Completed += (s, e) =>
                    {
                        acceptedSocket = e.AcceptSocket;
                        mainEvent.Set();
                    };

                } catch (Exception e) {
                    ex = e;
                    return;
                } finally {
                    readyEvent.Set();
                }

                try {
                    if (listenSocket.AcceptAsync(asyncEventArgs))
                        return;
                    acceptedSocket = asyncEventArgs.AcceptSocket;
                    mainEvent.Set();
                } catch (Exception e) {
                    ex = e;
                }
            });
            Assert.IsTrue(readyEvent.WaitOne(1500));
            if (ex != null)
                throw ex;

            var clientSocket = new Socket(
                AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(listenSocket.LocalEndPoint);
            clientSocket.NoDelay = true;

            Assert.IsTrue(mainEvent.WaitOne(1500));
            Assert.AreEqual(serverSocket, acceptedSocket, "x");
            mainEvent.Reset();

            if (acceptedSocket != null)
                acceptedSocket.Close();

            listenSocket.Close();
            readyEvent.Close();
            mainEvent.Close();
        }
開發者ID:ItsVeryWindy,項目名稱:mono,代碼行數:60,代碼來源:SocketAcceptAsyncTest.cs


注:本文中的System.Threading.ManualResetEvent.Reset方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。