• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# ManualResetEvent类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ManualResetEvent的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEvent类的具体用法?C# ManualResetEvent怎么用?C# ManualResetEvent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: Main

	/* expected exit code: 255 */
	static void Main (string[] args)
	{
		if (Environment.GetEnvironmentVariable ("TEST_UNHANDLED_EXCEPTION_HANDLER") != null)
			AppDomain.CurrentDomain.UnhandledException += (s, e) => {};

		ManualResetEvent mre = new ManualResetEvent (false);

		var a = new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } });
		var ares = a.BeginInvoke (null, null);

		if (!mre.WaitOne (5000))
			Environment.Exit (2);

		try {
			a.EndInvoke (ares);
			Environment.Exit (4);
		} catch (CustomException) {
			/* expected behaviour */
			Environment.Exit (255);
		} catch (Exception ex) {
			Console.WriteLine (ex);
			Environment.Exit (3);
		}

		Environment.Exit (5);
	}
开发者ID:ItsVeryWindy,项目名称:mono,代码行数:27,代码来源:unhandled-exception-2.cs


示例2: RunBlockedInjectionTest

        public static void RunBlockedInjectionTest()
        {
            Debug.WriteLine("* RunBlockedInjectionTest() -- if it deadlocks, it failed");

            ManualResetEvent mre = new ManualResetEvent(false);

            // we need to run this test in a local task scheduler, because it needs to to perform 
            // the verification based on a known number of initially available threads.
            //
            //
            // @TODO: When we reach the _planB branch we need to add a trick here using ThreadPool.SetMaxThread
            //        to bring down the TP worker count. This is because previous activity in the test process might have 
            //        injected workers.
            TaskScheduler tm = TaskScheduler.Default;

            // Create many tasks blocked on the MRE.

            int processorCount = Environment.ProcessorCount;
            Task[] tasks = new Task[processorCount];
            for (int i = 0; i < tasks.Length; i++)
            {
                tasks[i] = Task.Factory.StartNew(delegate { mre.WaitOne(); }, CancellationToken.None, TaskCreationOptions.None, tm);
            }

            // Create one task that signals the MRE, and wait for it.
            Task.Factory.StartNew(delegate { mre.Set(); }, CancellationToken.None, TaskCreationOptions.None, tm).Wait();

            // Lastly, wait for the others to complete.
            Task.WaitAll(tasks);
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:30,代码来源:TaskSchedulerTests.cs


示例3: TestWaitAny

	public void TestWaitAny()
	{
		int x;

		e1 = new ManualResetEvent(false);
		e2 = new ManualResetEvent(false);

		x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2}, 100,false);

		AssertEquals("WaitAny(unset, unset)", x, WaitHandle.WaitTimeout);

		e1.Set();

		x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAny(set, unset)", x, 0);

		e1.Reset();
		e2.Set();

		x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAny(set, unset)", x, 1);

		e1.Set();
		e2.Set();

		x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAny(set, set)", x, 0);
	}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:31,代码来源:TestWaitHandle.cs


示例4: TestWaitAll

	public void TestWaitAll()
	{
		bool x;

		e1 = new ManualResetEvent(false);
		e2 = new ManualResetEvent(false);

		x = WaitHandle.WaitAll(new WaitHandle[] {e1,e2}, 100,false);

		AssertEquals("WaitAll(unset, unset)", x, false);

		e1.Set();

		x = WaitHandle.WaitAll(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAll(set, unset)", x, false);

		e1.Reset();
		e2.Set();

		x = WaitHandle.WaitAll(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAll(set, unset)", x, false);

		e1.Set();
		e2.Set();

		x = WaitHandle.WaitAll(new WaitHandle[] {e1,e2},100, true);

		AssertEquals("WaitAll(set, set)", x, true);
	}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:31,代码来源:TestWaitHandle.cs


示例5: Main

    public static void Main()
    {     	
    	e = new ManualResetEvent(false);

   	
        // Create the waiter thread's group
        Console.WriteLine("[  Main  ] - Creating first thread..");
        ThreadStart Thread_1 = new ThreadStart(ThreadMethod_waiter_1);
        ThreadStart Thread_2 = new ThreadStart(ThreadMethod_waiter_2);
        
        // Create the blocker thread
        Console.WriteLine("[  Main  ] - Creating second thread..");
        ThreadStart Thread_3 = new ThreadStart(ThreadMethod_blocker);

        Thread A = new Thread(Thread_1);
        Thread B = new Thread(Thread_2);
        Thread C = new Thread(Thread_3);
        
	A.Start();
    	B.Start();
    	C.Start();
    	
    	Thread.Sleep(500);
    	Console.WriteLine("[  Main  ] - Finish...");
    }
开发者ID:Zman0169,项目名称:mono,代码行数:25,代码来源:manualresetevents.cs


示例6: Terminate

	void Terminate()
	{

		if (ms_Instance == null || ms_Instance != this || !AkSoundEngine.IsInitialized())
			return; //Don't term twice        
				
		// Mop up the last callbacks that will be sent from Term with blocking.  
		// It may happen that the term sends so many callbacks that it will use up 
		// all the callback memory buffer and lock the calling thread. 

		// WG-25356 Thread is unsupported in Windows Store App API.

		AkSoundEngine.StopAll();
		AkSoundEngine.RenderAudio();
		const double IdleMs = 1.0;
		const uint IdleTryCount = 50;
		for(uint i=0; i<IdleTryCount; i++)
		{
			AkCallbackManager.PostCallbacks();
			using (EventWaitHandle tmpEvent = new ManualResetEvent(false)) {
				tmpEvent.WaitOne(System.TimeSpan.FromMilliseconds(IdleMs));
			}
		}

		AkSoundEngine.Term();
	
		ms_Instance = null;

		AkCallbackManager.Term();
		AkBankManager.Reset ();
	}
开发者ID:mattlazarte,项目名称:AscentUnityProject,代码行数:31,代码来源:AkTerminator.cs


示例7: PosTest2

    public bool PosTest2()
    {
        bool retVal = true;

        ManualResetEvent expectedValue = new ManualResetEvent(false);
        ManualResetEvent actualValue;

        TestLibrary.TestFramework.BeginScenario("PosTest2:Set initialState as false and Create a instance");
        try
        {
            actualValue = (ManualResetEvent)(new ManualResetEvent(false));
            if (expectedValue.Equals(actualValue))
            {
                TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e);
            retVal = false;
        }
        return retVal;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:25,代码来源:manualreseteventctor.cs


示例8: EvalPerf

	private static void EvalPerf(Synch synch, int numThreads) {
		ManualResetEvent startEvent = new ManualResetEvent(false);
		int endTime = 0;
		int totalOps = 0;
		
		Thread[] threads = new Thread[numThreads];
		for (int n = 0; n < numThreads; ++n) {
			threads[n] = new Thread(() => {
				int numOps = 0; 
				startEvent.WaitOne();
				
				do {
					for (int i = 0; i < LOCKS_PER_LOOP; ++i) {
						synch.Synchronize(() => {
							// Busy variant:
                     // Thread.Yield();
						});
					}
					numOps += LOCKS_PER_LOOP;
				} while (Environment.TickCount < endTime);
				
				Interlocked.Add(ref totalOps, numOps);
			});
			threads[n].Start();
		}
		
		endTime = Environment.TickCount + MS_PER_TEST;
		startEvent.Set();
		
		foreach (Thread t in threads) {
			t.Join();
		}
		Console.WriteLine("[{0}] {1}", numThreads, totalOps);
	}
开发者ID:Skyish,项目名称:isel-pc-1516-1,代码行数:34,代码来源:SpinLockPerf.cs


示例9: Main

	/* expected exit code: 255 */
	static void Main (string[] args)
	{
		if (Environment.GetEnvironmentVariable ("TEST_UNHANDLED_EXCEPTION_HANDLER") != null)
			AppDomain.CurrentDomain.UnhandledException += (s, e) => {};

		ManualResetEvent mre = new ManualResetEvent (false);

		var t = Task.Factory.StartNew (new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } }));

		if (!mre.WaitOne (5000))
			Environment.Exit (2);

		try {
			t.Wait ();
			Environment.Exit (5);
		} catch (AggregateException ae) {
			Console.WriteLine (ae);
			if (ae.InnerExceptions [0] is CustomException) {
				/* expected behaviour */
				Environment.Exit (255);
			}
		} catch (Exception ex) {
			Console.WriteLine (ex);
			Environment.Exit (3);
		}

		Environment.Exit (6);
	}
开发者ID:ItsVeryWindy,项目名称:mono,代码行数:29,代码来源:unhandled-exception-4.cs


示例10: Initialize

		// Initialize Parallel class's instance creating required number of threads
		// and synchronization objects
		private void Initialize( )
		{
			threadsCount = System.Environment.ProcessorCount;
			
			//No point starting new threads for a single core computer
			if (threadsCount <= 1) {
				return;
			}
			
			// array of events, which signal about available job
			jobAvailable = new AutoResetEvent[threadsCount];
			// array of events, which signal about available thread
			threadIdle = new ManualResetEvent[threadsCount];
			// array of threads
			threads = new Thread[threadsCount];
		
			for ( int i = 0; i < threadsCount; i++ )
			{
				jobAvailable[i] = new AutoResetEvent( false );
				threadIdle[i]   = new ManualResetEvent( true );
		
				threads[i] = new Thread( new ParameterizedThreadStart( WorkerThread ) );
				threads[i].IsBackground = false;
				threads[i].Start( i );
			}
		}
开发者ID:pravusjif,项目名称:PravusUnityTests,代码行数:28,代码来源:Parallel.cs


示例11: Main

	public static int Main ()
	{
		main_thread_id = Thread.CurrentThread.ManagedThreadId;
		Console.WriteLine ("{0}:Main start", main_thread_id);

		mre = new ManualResetEvent (false);
		mre2 = new ManualResetEvent (false);
		tcs = new TaskCompletionSource<bool> ();

		Task.Factory.StartNew (new Func<Task> (ExecuteAsync), new CancellationToken (), TaskCreationOptions.LongRunning, TaskScheduler.Default);

		if (!mre.WaitOne (1000))
			return 1;

		// Have to wait little bit longer for await not to take quick path
		Thread.Sleep (10);

		Console.WriteLine ("{0}:Main Set Result", Thread.CurrentThread.ManagedThreadId);

		SynchronizationContext.SetSynchronizationContext (new MyContext ());

		tcs.SetResult (true);

		if (!mre2.WaitOne (1000))
			return 2;

		Console.WriteLine ("ok");
		return 0;
	}
开发者ID:nobled,项目名称:mono,代码行数:29,代码来源:test-async-55.cs


示例12: PropertyTest1

    public static void PropertyTest1()
    {
        IAsyncResult asyncResult = new Task(() => Console.WriteLine("this is a dummy task"));
        var obj = new Overlapped();

        Assert.Null(obj.AsyncResult);
        obj.AsyncResult = asyncResult;
        Assert.Same(obj.AsyncResult, asyncResult);

#pragma warning disable 618
        Assert.Equal(obj.EventHandle, 0);
        obj.EventHandle = 3;
        Assert.Equal(obj.EventHandle, 3);
#pragma warning restore 618

        var _handle = new ManualResetEvent(false).SafeWaitHandle;
        Assert.NotSame(obj.EventHandleIntPtr, IntPtr.Zero);
        obj.EventHandleIntPtr = _handle.DangerousGetHandle();
        Assert.Equal(obj.EventHandleIntPtr, _handle.DangerousGetHandle());

        Assert.Equal(obj.OffsetHigh, 0);
        obj.OffsetHigh = 3;
        Assert.Equal(obj.OffsetHigh, 3);

        Assert.Equal(obj.OffsetLow, 0);
        obj.OffsetLow = 1;
        Assert.Equal(obj.OffsetLow, 1);
    }
开发者ID:chcosta,项目名称:corefx,代码行数:28,代码来源:OverlappedTests.cs


示例13: BlockQueueUntilBelowBoundedCapacity

            public void BlockQueueUntilBelowBoundedCapacity()
            {
                var monitor = new FakeMonitor();
                var threadPool = new FakeThreadPool();
                var blocked = new ManualResetEvent(false);
                var released = new ManualResetEvent(false);
                var taskScheduler = new BlockingThreadPoolTaskScheduler(1, threadPool, monitor);

                monitor.BeforeWait = () => blocked.Set();
                monitor.AfterPulse = () => released.Set();

                Task.Factory.StartNew(() =>
                    {
                        // Schedule first task (non-blocking).
                        Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);

                        // Schedule second task (blocking).
                        Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
                    });

                // Wait for second task to be blocked.
                Assert.True(blocked.WaitOne(TimeSpan.FromMilliseconds(100)));
                Assert.Equal(1, threadPool.UserWorkItems.Count);

                threadPool.RunNext();

                // Wait for second task to be released.
                Assert.True(released.WaitOne(TimeSpan.FromMilliseconds(100)));

                threadPool.RunNext();

                Assert.Equal(0, taskScheduler.ScheduledTasks.Count());
            }
开发者ID:SparkSoftware,项目名称:infrastructure,代码行数:33,代码来源:BlockingThreadPoolTaskSchedulerTests.cs


示例14: Test1

	static void Test1 (Process p)
	{
		ManualResetEvent mre_exit = new ManualResetEvent (false);
		ManualResetEvent mre_output = new ManualResetEvent (false);
		ManualResetEvent mre_error = new ManualResetEvent (false);

		p.EnableRaisingEvents = true;
		p.Exited += (s, a) => mre_exit.Set ();

		p.Start ();

		p.OutputDataReceived += (s, a) => {
			if (a.Data == null) {
				mre_output.Set ();
				return;
			}
		};

		p.ErrorDataReceived += (s, a) => {
			if (a.Data == null) {
				mre_error.Set ();
				return;
			}
		};

		p.BeginOutputReadLine ();
		p.BeginErrorReadLine ();

		if (!mre_exit.WaitOne (10000))
			Environment.Exit (1);
		if (!mre_output.WaitOne (1000))
			Environment.Exit (2);
		if (!mre_error.WaitOne (1000))
			Environment.Exit (3);
	}
开发者ID:ItsVeryWindy,项目名称:mono,代码行数:35,代码来源:process-stress-3.cs


示例15: Start

 public void Start()
 {
     // create a new ManualResetEvent. This will be used to make the main application
     // thread wait until the full server reply has been received.
     m_ResetEvent = new ManualResetEvent(false);
     // initialize the security options
     SecurityOptions options = new SecurityOptions(
         SecureProtocol.Ssl3 | SecureProtocol.Tls1,	// use SSL3 or TLS1
         null,										// do not use client authentication
         ConnectionEnd.Client,						// this is the client side
         CredentialVerification.None,				// do not check the certificate -- this should not be used in a real-life application :-)
         null,										// not used with automatic certificate verification
         "www.microsoft.com",						// this is the common name of the Microsoft web server
         SecurityFlags.Default,						// use the default security flags
         SslAlgorithms.SECURE_CIPHERS,				// only use secure ciphers
         null);										// do not process certificate requests.
     try {
         // create the securesocket with the specified security options
         m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
         // resolve www.microsoft.com
         IPEndPoint endpoint = new IPEndPoint(Dns.GetHostEntry("www.microsoft.com").AddressList[0], 443);
         // start connecting to www.microsoft.com
         m_Socket.BeginConnect(endpoint, new AsyncCallback(this.OnConnect), null);
         // wait until the entire web page has been received
         m_ResetEvent.WaitOne();
         // close the SecureSocket
         m_Socket.Close();
     } catch {
         OnError("Could not connect to the website");
     }
 }
开发者ID:maikgreubel,项目名称:securitylibrary,代码行数:31,代码来源:AsynchronousSocket.cs


示例16: Test2

	static void Test2 (Process p)
	{
		ManualResetEvent mre_output = new ManualResetEvent (false);
		ManualResetEvent mre_error = new ManualResetEvent (false);

		p.Start ();

		p.OutputDataReceived += (s, a) => {
			if (a.Data == null) {
				mre_output.Set ();
				return;
			}
		};

		p.ErrorDataReceived += (s, a) => {
			if (a.Data == null) {
				mre_error.Set ();
				return;
			}
		};

		p.BeginOutputReadLine ();
		p.BeginErrorReadLine ();

		if (!p.WaitForExit (10000))
			Environment.Exit (4);
		if (!mre_output.WaitOne (1000))
			Environment.Exit (5);
		if (!mre_error.WaitOne (1000))
			Environment.Exit (6);
	}
开发者ID:ItsVeryWindy,项目名称:mono,代码行数:31,代码来源:process-stress-3.cs


示例17: AbortSuspendTest

        public static void AbortSuspendTest()
        {
            var e = new ManualResetEvent(false);
            Action waitForThread;
            var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
            t.IsBackground = true;

            Action verify = () =>
            {
                Assert.Throws<PlatformNotSupportedException>(() => t.Abort());
                Assert.Throws<PlatformNotSupportedException>(() => t.Abort(t));
            #pragma warning disable 618 // Obsolete members
                Assert.Throws<PlatformNotSupportedException>(() => t.Suspend());
                Assert.Throws<PlatformNotSupportedException>(() => t.Resume());
            #pragma warning restore 618 // Obsolete members
            };
            verify();

            t.Start();
            verify();

            e.Set();
            waitForThread();

            Assert.Throws<PlatformNotSupportedException>(() => Thread.ResetAbort());
        }
开发者ID:dotnet,项目名称:corefx,代码行数:26,代码来源:ThreadTests.netstandard1.7.cs


示例18: Run

 private int Run()
 {
     int iRet = -1;
     Console.WriteLine("Abandoning more than one mutex " +
         "mix with other WaitHandles");
     CreateArray(64);
     myMRE = new ManualResetEvent(false);
     Thread t = new Thread(new ThreadStart(this.AbandonAllMutexes));
     t.Start();
     myMRE.WaitOne();
     try
     {
         Console.WriteLine("Waiting...");
         int i = WaitHandle.WaitAny(wh);
         Console.WriteLine("WaitAny did not throw an " +
             "exception, i = " + i);
     }
     catch(AbandonedMutexException)
     {
         // Expected
         iRet = 100;
     }
     catch(Exception e)
     {
         Console.WriteLine("Unexpected exception thrown: " + 
             e.ToString());
     }
     Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
     return iRet;
 }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:30,代码来源:waitanyex3a.cs


示例19: PingPong

 public void PingPong()
 {
     using (ManualResetEvent mre1 = new ManualResetEvent(true), mre2 = new ManualResetEvent(false))
     {
         const int Iters = 10;
         Task.WaitAll(
             Task.Factory.StartNew(() =>
             {
                 for (int i = 0; i < Iters; i++)
                 {
                     Assert.True(mre1.WaitOne(FailedWaitTimeout));
                     mre1.Reset();
                     mre2.Set();
                 }
             }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default),
             Task.Factory.StartNew(() =>
             {
                 for (int i = 0; i < Iters; i++)
                 {
                     Assert.True(mre2.WaitOne(FailedWaitTimeout));
                     mre2.Reset();
                     mre1.Set();
                 }
             }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
     }
 }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:26,代码来源:ManualResetEventTests.cs


示例20: TestHelper

	public TestHelper(int num)
	{
		m_Event = new ManualResetEvent(false);
		m_iSharedData = 0;
		m_iRequestedEntries = num;
		m_bError = false;
	}
开发者ID:CheneyWu,项目名称:coreclr,代码行数:7,代码来源:MonitorHelper.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Manufacturer类代码示例发布时间:2022-05-24
下一篇:
C# ManosAction类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap