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


C# ManualResetEvent.Set方法代码示例

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


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

示例1: ThreadGlobalTimeServerIsShared

        public void ThreadGlobalTimeServerIsShared()
        {
            var ts1 = new TestDateTimeServer(now: new DateTime(2011, 1, 1));
            var ts2 = new TestDateTimeServer(now: new DateTime(2012, 1, 1));

            var g1 = new ManualResetEvent(false);
            var g2 = new ManualResetEvent(false);

            DateTime? t1Date = null;

            var t1 = new Thread(() => {
                DateTimeServer.SetGlobal(ts1);
                g1.WaitOne();
                t1Date = DateTimeServer.Now;
                g2.Set();
            });

            var t2 = new Thread(() => {
                DateTimeServer.SetGlobal(ts2);
                g2.Set();
                g1.WaitOne();
            });

            t1.Start();
            t2.Start();

            Assert.That(g2.WaitOne(20), Is.True);
            g2.Reset();
            g1.Set();
            Assert.That(g2.WaitOne(20), Is.True);

            Assert.That(t1Date, Is.Not.Null);
            Assert.That(t1Date, Is.EqualTo(ts2.Now));
        }
开发者ID:andy-uq,项目名称:HomeTrack,代码行数:34,代码来源:DateTimeServerTests.cs

示例2: MarkForDeletion

        /// <summary>
        /// Marks message as deleted.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception>
        public void MarkForDeletion()
        {
            if(this.IsDisposed){
                throw new ObjectDisposedException(this.GetType().Name);
            }
            if(this.IsMarkedForDeletion){
                return;
            }

            using(MarkForDeletionAsyncOP op = new MarkForDeletionAsyncOP()){
                using(ManualResetEvent wait = new ManualResetEvent(false)){
                    op.CompletedAsync += delegate(object s1,EventArgs<MarkForDeletionAsyncOP> e1){
                        wait.Set();
                    };
                    if(!this.MarkForDeletionAsync(op)){
                        wait.Set();
                    }
                    wait.WaitOne();
                    wait.Close();

                    if(op.Error != null){
                        throw op.Error;
                    }
                }
            }
        }
开发者ID:dioptre,项目名称:nkd,代码行数:31,代码来源:POP3_ClientMessage.cs

示例3: WebBrowser

        public WebBrowser(Arguments args)
            : this()
        {
            var address = args["address"].Value as string;

            DispatcherThread.StartNew(() =>
            {
                //TODO: Add ability to define browser settings.
                if (address != null)
                    m_webBrowser = new ChromiumWebBrowser(address);
                else
                    m_webBrowser = new ChromiumWebBrowser("");

            }).Wait();

            //Ensure that the web browser is initialized.
            using (var evt = new ManualResetEvent(false))
            {
                m_webBrowser.BrowserInitialized += (o, e) => evt.Set();

                DispatcherThread.StartNew(() =>
                {

                    if (m_webBrowser.IsBrowserInitialized)
                    {
                        evt.Set();
                    }
                });

                evt.WaitOne();
            }
        }
开发者ID:Oceanswave,项目名称:SkraprSharp,代码行数:32,代码来源:WebBrowser.cs

示例4: ExecuteSync

        public static void ExecuteSync(string key, string command, Action<Action<object>, Action<Exception, object>> action)
        {
            var resetEvent = new ManualResetEvent(initialState: false);
            Exception exception = null;

            action(
                //delegate to invoke on success
                s => resetEvent.Set(),

                //delegate to invoke on test error
                (e, s) =>
                {
                    exception = e;
                    resetEvent.Set();
                });

            var timeout = KetchupConfig.Current.SyncCommandTimeout;
            if (!resetEvent.WaitOne(timeout * 1000))
                throw new TimeoutException(
                    string.Format(
                        "Command timed out on before async response was returned.\nCommand: {0}\nKey: {1}",
                        command,
                        key
                    ));

            if (exception != null)
                throw exception;
        }
开发者ID:jasonsirota,项目名称:Ketchup,代码行数:28,代码来源:SyncExtensions.cs

示例5: CloseTest

        public void CloseTest()
        {
            int shutdownCount = 0;
            int closeCount = 0;

            ManualResetEvent resetEvent = new ManualResetEvent(false);

            NetworkConnection connection = new NetworkConnection(_client);

            connection.Shutdown += (sender, args) =>
            {
                shutdownCount++;
                resetEvent.Set();
            };

            connection.ConnectionClosed += (sender, args) =>
            {
                closeCount++;
                resetEvent.Set();
            };

            connection.Start();
            connection.Close();

            Assert.That(resetEvent.WaitOne(2000));
            Assert.That(shutdownCount, Is.EqualTo(0));
            Assert.That(closeCount, Is.EqualTo(1));
        }
开发者ID:williamoneill,项目名称:Gallatin,代码行数:28,代码来源:NetworkConnectionTests.cs

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

示例7: NatsClient_PubSub_Queue

        public void NatsClient_PubSub_Queue()
        {
            string recvMsg = null;
            int counter = 0;
            using (var nats1 = new NatsClient(NatsUrl))
            using (var nats2 = new NatsClient(NatsUrl))
            using (var waitHandle = new ManualResetEvent(false))
            {
                nats1.Connect();
                nats1.Subscribe("test", new Options("queue"), (msg, source) => {
                    Console.WriteLine("Received: {0}", msg);
                    recvMsg = msg;
                    counter += 1;
                    waitHandle.Set();
                });

                nats2.Connect();
                nats2.Subscribe("test", new Options("queue"), (msg, source) =>
                {
                    Console.WriteLine("Received: {0}", msg);
                    recvMsg = msg;
                    counter += 1;
                    waitHandle.Set();
                });

                nats2.Publish("test", "Hello");
                waitHandle.WaitOne(1000);
            }
            Assert.AreEqual("Hello", recvMsg);
            Assert.AreEqual(1, counter);
        }
开发者ID:vchs,项目名称:nats_client_dotnet,代码行数:31,代码来源:NatsClientTest.cs

示例8: TestPolling

        public void TestPolling()
        {
            var reddit = new RedditClient(() => new HttpClient());

            var pollingClient = new RedditPollingClient(reddit, "funny", TimeSpan.FromSeconds(10), ex => { });

            var resetEvent = new ManualResetEvent(false);

            var subscription = pollingClient.Posts.Subscribe(
                x => Debug.WriteLine($"New post: {x.Title}"),
                ex =>
                {
                    Debug.WriteLine($"Error while retrieving reddit posts: {ex.Message}");
                    resetEvent.Set();
                },
                () =>
                {
                    Debug.WriteLine("Finished retrieving posts");
                    resetEvent.Set();
                });

            pollingClient.Start();

            resetEvent.WaitOne(60000);
        }
开发者ID:RagtimeWilly,项目名称:Rxddit,代码行数:25,代码来源:RedditPollingClientTests.cs

示例9: GetConfig_CanLoadConfigsFromMultipleThreads

		public void GetConfig_CanLoadConfigsFromMultipleThreads() {

			const string configKey = "MyCustomConfig";
			var configLoader = new FakeLoader(false, true);
			var configRepository = new ConfigRepository(configLoader);

			const int maxThreads = 10;

			Exception ex = null;
			IConfig config = null;

			var getConfigCompletedEvent = new ManualResetEvent(false);
			for(int i = 0; i < maxThreads; i++) {
				int remainingThreads = i;
				ThreadPool.QueueUserWorkItem(s => {
					try {
						config = configRepository.GetConfig(configKey, false);
						if(Interlocked.Decrement(ref remainingThreads) == 0) {
							getConfigCompletedEvent.Set();
						}
					} catch(Exception innerEx) {
						getConfigCompletedEvent.Set();
						ex = innerEx;
						throw;
					}
				});
			}
			getConfigCompletedEvent.WaitOne();
			getConfigCompletedEvent.Close();
			Assert.IsNotNull(config);
			Assert.IsNull(ex);
			
		}
开发者ID:aelveborn,项目名称:njupiter,代码行数:33,代码来源:ConfigRepositoryTests.cs

示例10: IterateErrorHandlingTest

		public void IterateErrorHandlingTest()
		{
			var xs = Enumerable.Range(0, 10).Select(x => Observable.Return(new Data(x)));
			int errors = 0;
			Func<IObservable<Data>> createOriginSource = () => TpObservableExtensions.Iterate(xs, x =>
				{
					if (x.Body != 5)
					{
						Console.WriteLine("Handler: " + x.Body);
					}
					else
					{
						throw new ApplicationException();
					}
				}, Scheduler.ThreadPool, s => Console.WriteLine("Trace: " + s));
			var ev = new ManualResetEvent(false);
			var source = TpObservableExtensions.ToSelfRepairingHotObservable(createOriginSource, _ => { }, e =>
				{
					Console.WriteLine(e);
					errors++;
					if (errors == 5)
					{
						ev.Set();
					}
				});
			using (source.Subscribe(x => Console.WriteLine("Observer: " + x.Body), Console.WriteLine, () =>
																											{
																												ev.Set();
																												Console.WriteLine("Observer: completed");
																											}))
			{
				ev.WaitOne(TimeSpan.FromSeconds(5)).Should(Be.True);
			}
		}
开发者ID:sbcfwebdev,项目名称:Target-Process-Plugins,代码行数:34,代码来源:ObservableExtensionsTest.cs

示例11: Loaders_are_thread_safe

		public void Loaders_are_thread_safe()
		{
		    kernel.Register(Component.For<SlowLoader>());
		    var @event = new ManualResetEvent(false);
			int[] count = {10};
			Exception exception = null;
			for (int i = 0; i < count[0]; i++)
			{
				ThreadPool.QueueUserWorkItem(o =>
				                             	{
				                             		try
				                             		{
				                             			kernel.Resolve<Implementation>("not registered");
				                             			if (Interlocked.Decrement(ref count[0]) == 0)
				                             			{
				                             				@event.Set();
				                             			}
				                             		}
				                             		catch (Exception e)
				                             		{
				                             			exception = e;
				                             			// this is required because NUnit does not consider it a failure when
				                             			// an exception is thrown on a non-main thread and therfore it waits.
				                             			@event.Set();
				                             		}
				                             	}
					);
			}
			@event.WaitOne();
			Assert.IsNull(exception);
			Assert.AreEqual(0, count[0]);
		}
开发者ID:gschuager,项目名称:Castle.Windsor,代码行数:32,代码来源:LazyLoadingTestCase.cs

示例12: GetTokens

        /// <summary>
        /// Get the OAuth tokens required to access the cloud based API (Synchronous)
        /// </summary>
        /// <param name="code">The code received after the user has given the application permission to access their company files</param>
        /// <returns>The tokens that are required to access the user's company files</returns>
        public OAuthTokens GetTokens(string code)
        {
            var wait = new ManualResetEvent(false);
            OAuthTokens oauthTokens = null;
            Exception ex = null;
            var requestUri = default(Uri);

            GetTokens(code,
                (statusCode, tokens) =>
                    {
                        oauthTokens = tokens;
                        wait.Set();
                    },
                (uri, exception) =>
                    {
                        requestUri = uri;
                        ex = exception;
                        wait.Set();
                    });

            if (wait.WaitOne(new TimeSpan(0, 0, 0, 60)))
            {
                ex.ProcessException(requestUri);
            }

            return oauthTokens;
        }
开发者ID:kgreed,项目名称:AccountRight_Live_API_.Net_SDK,代码行数:32,代码来源:OAuthService.cs

示例13: DownloadData

        /// <summary>
        /// Downloads the resource as a string from the URI specified.
        /// </summary>
        /// <param name="address">The URI represented by the Uri object, from which to download data.</param>
        /// <returns></returns>
        public string DownloadData(Uri address)
        {
            var initRequest = (HttpWebRequest)WebRequest.Create(address);
            var result = String.Empty;
            var responseComplete = new ManualResetEvent(false);

            if (Headers != null) initRequest.Headers = Headers;

            initRequest.BeginGetResponse(ar =>
            {
                var signaled = false;
                try
                {
                    var response = GetResponse(ar);

                    result = ReadResponseToString(response);

                    responseComplete.Set();

                    signaled = true;
                }
                catch (Exception)
                {
                    if (!signaled)
                    {
                        responseComplete.Set();
                    }
                }
            }, initRequest);

            return result;
        }
开发者ID:NicePeopleAtWork,项目名称:NicePlayers,代码行数:37,代码来源:SilverlightWebClient.cs

示例14: SimpleCommunication

        public void SimpleCommunication()
        {
            var reset1 = new ManualResetEvent(false);
            var reset2 = new ManualResetEvent(false);

            INatterConnection connection2 = null;
            var connection1 =_client1.OnConnected(c => reset1.Set()).OnData((c, f) => HandleResponse(f, c)).Call(GetClient2Address());
            _client2.OnConnected(c => reset2.Set()).OnData((c, f) => { HandleResponse(f, c); connection2 = c; });
            Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect");
            Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect");

            reset1.Reset();
            reset2.Reset();
            _client1.OnDisconnected(c => reset1.Set());
            _client2.OnDisconnected(c => reset2.Set());
            Send(connection1, StartNumber);

            Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect");
            Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect");
            Assert.AreEqual(ConnectionState.Disconnected, connection1.State, "Client not disconnected");
            Assert.AreEqual(ConnectionState.Disconnected, connection2.State, "Client not disconnected");

            Assert.AreEqual(EndNumber, _lastResult, "Invalid last number");
            Assert.AreEqual((EndNumber - StartNumber) + 1, _count, "Invalid count");
        }
开发者ID:KevWK314,项目名称:Natter,代码行数:25,代码来源:CommunicationTest.cs

示例15: ExecuteActionAndWait

        /// <summary>
        /// Executes a specified method and waits until the action is completed
        /// </summary>
        /// <param name="action">The action.</param>
        public static void ExecuteActionAndWait(Action<IAsyncContinuation> action)
        {
            var waitHandle = new ManualResetEvent(false);
            Exception exception = null;
            var continuation = AsyncHelpers.CreateContinuation(
                () => waitHandle.Set(),
                exc =>
                {
                    exception = exc;
                    waitHandle.Set();
                });

            // try it synchronously, otherwise wait
            action(continuation);

            bool signalOccurred = WaitHandle.WaitAll(new WaitHandle[] { waitHandle }, MaxMillisecondsTimeout);

            if (!signalOccurred)
            {
                throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The action has not completed within {0} milliseconds", MaxMillisecondsTimeout));
            }

            if (exception != null)
            {
                // wrap the exception to preserve the original call-stack
                throw new TaupoInfrastructureException("An exception occurred during asynchronous execution", exception);
            }
        }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:32,代码来源:SyncHelpers.cs


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