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


C# Threading.WaitHandle類代碼示例

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


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

示例1: WorkerThreadLoop

        private void WorkerThreadLoop()
        {
            WaitHandle[] waitHandles = new WaitHandle[2] { _stopEvent, _workerParseEvent };
            while (true)
            {
                int wait = WaitHandle.WaitAny(waitHandles);
                if (wait == 0)
                    return;

                //Drain the work queue
                while (true)
                {
                    ParseJob job = null;
                    lock (_lock)
                    {
                        if (_work.Count > 0)
                        {
                            job = _work.First();
                            _work.RemoveAt(0);
                        }
                        else
                        {
                            break;
                        }
                    }
                    Parse(job);
                }
            }
        }
開發者ID:JadeHub,項目名稱:Jade,代碼行數:29,代碼來源:Parser.cs

示例2: TestQueryWithContainsInParallel

		public void TestQueryWithContainsInParallel()
		{
			var ids = new List<Guid>
			{
				Guid.NewGuid(),
				Guid.NewGuid(),
			};
			const int threadsToRun = 32;
			var events = new WaitHandle[threadsToRun];
			var exceptions = new List<Exception>();
			for (var i = 0; i < threadsToRun; i++)
			{
				var @event = new ManualResetEvent(false);
				events[i] = @event;
				ThreadPool.QueueUserWorkItem(s =>
				{
					try
					{
						Run(ids);
					}
					catch (Exception ex)
					{
						exceptions.Add(ex);
					}
					finally
					{
						@event.Set();
					}
				});
			}
			WaitHandle.WaitAll(events);
			Assert.IsEmpty(exceptions);
		}
開發者ID:NikGovorov,項目名稱:nhibernate-core,代碼行數:33,代碼來源:Fixture.cs

示例3: CheckArray

		static void CheckArray (WaitHandle [] handles, bool waitAll)
		{
			if (handles == null)
				throw new ArgumentNullException ("waitHandles");

			int length = handles.Length;
			if (length > 64)
				throw new NotSupportedException ("Too many handles");

#if false
			//
			// Although we should thrown an exception if this is an STA thread,
			// Mono does not know anything about STA threads, and just makes
			// things like Paint.NET not even possible to work.
			//
			// See bug #78455 for the bug this is supposed to fix. 
			// 
			if (waitAll && length > 1 && IsSTAThread)
				throw new NotSupportedException ("WaitAll for multiple handles is not allowed on an STA thread.");
#endif
			foreach (WaitHandle w in handles) {
				if (w == null)
					throw new ArgumentNullException ("waitHandles", "null handle");

#if NET_2_0
				if (w.safe_wait_handle == null)
					throw new ArgumentException ("null element found", "waitHandle");
#else
				if (w.os_handle == InvalidHandle)
					throw new ArgumentException ("null element found", "waitHandle");
#endif
			}
		}
開發者ID:runefs,項目名稱:Marvin,代碼行數:33,代碼來源:WaitHandle.cs

示例4: DoTest

        private static void DoTest()
        {
            _application = new Excel.Application();
            Excel.Workbook book = _application.Workbooks.Add();

            WaitHandle[] waitHandles = new WaitHandle[3];

            Thread thread1 = new Thread(new ParameterizedThreadStart(Thread1Method));
            Thread thread2 = new Thread(new ParameterizedThreadStart(Thread2Method));
            Thread thread3 = new Thread(new ParameterizedThreadStart(Thread3Method));

            ManualResetEvent mre1 = new ManualResetEvent(false);
            ManualResetEvent mre2 = new ManualResetEvent(false);
            ManualResetEvent mre3 = new ManualResetEvent(false);

            waitHandles[0] = mre1;
            waitHandles[1] = mre2;
            waitHandles[2] = mre3;

            thread1.Start(mre1);
            thread2.Start(mre2);
            thread3.Start(mre3);

            WaitHandle.WaitAll(waitHandles);

            _application.Quit();
            _application.Dispose();
        }
開發者ID:vnkolt,項目名稱:NetOffice,代碼行數:28,代碼來源:Program.cs

示例5: EnumerateWindows

        /// <summary>
        /// Enumerates all top level windows on desktop. WARNING: The method returns null if operation timeout is reached.
        /// </summary>
        /// <param name="milliSecondsTimeout">a timeout for the operation. when a desktop is busy or non responding these method freeze. you can handle this with the operation timeout</param>
        /// <returns>Result Array or null</returns>
        public IntPtr[] EnumerateWindows(int milliSecondsTimeout)
        {
            try
            {
                lock (_lockInstance)
                {
                    Result.Clear();
                    _currentInstance = this;
                    Thread thread1 = new Thread(new ParameterizedThreadStart(EnumerateWindowsAsync));
                    WaitHandle[] waitHandles = new WaitHandle[1];
                    ManualResetEvent mre1 = new ManualResetEvent(false);
                    waitHandles[0] = mre1;
                    thread1.Start(mre1);
                    bool result = WaitHandle.WaitAll(waitHandles, milliSecondsTimeout);
                    if (!result)
                    {
                        thread1.Abort();
                        Result.Clear();
                        _currentInstance = null;
                        return null;
                    }
                    else
                    {
                        _currentInstance = null;
                    }

                }
                return Result.ToArray();
            }
            catch (Exception exception)
            {
                DebugConsole.Default.WriteException(exception);
                throw;
            }
        }
開發者ID:netintellect,項目名稱:NetOffice,代碼行數:40,代碼來源:WindowEnumerator.cs

示例6: ShowDialog

        public DialogResult ShowDialog(MobileRemoteUI parentForm, WaitHandle waitResult, AddressSelector.BluetoothDevice device, BluetoothHidWriter hidWriter)
        {
            _statusLabel.Text = "Connecting...";
            _hidWriter = hidWriter;
            _waitResult = waitResult;
            if (device.Address > 0)
            {
                _existingMachine.Dock = DockStyle.Fill;
                _existingMachine.Visible = true;
                _newMachineLabel.Visible = false;
            }
            else
            {
                _newMachineLabel.Dock = DockStyle.Fill;
                _newMachineLabel.Visible = true;
                _existingMachine.Visible = false;
            }

            timer1.Enabled = true;

            if (waitResult.WaitOne(1000, false))
            {
                //return DialogResult.OK;
            }

            try
            {
                return base.ShowDialog(parentForm);
            }
            finally
            {
                timer1.Enabled = false;
            }
        }
開發者ID:nbclark,項目名稱:mobile-remote,代碼行數:34,代碼來源:WaitForConnection.cs

示例7: WaitForComplete

      public static WaitReturn WaitForComplete(double mill, WaitHandle wh)
      {
         TimeSpan goal = new TimeSpan(DateTime.Now.AddMilliseconds(mill).Ticks);
         MSG msg = new MSG();
         HandleRef h = new HandleRef(null, IntPtr.Zero);

         do
         {
            if(PeekMessage(out msg, h, 0, 0, PM_REMOVE))
            {
                  TranslateMessage(ref msg);
                  DispatchMessage(ref msg);
               }

            if(wh.WaitOne(new TimeSpan(1), false))
            {
               return WaitReturn.Complete;
            }

            if(goal.CompareTo(new TimeSpan(DateTime.Now.Ticks)) < 0)
            {
               return WaitReturn.Timeout;
            }

         } while(true);
      }
開發者ID:khaha2210,項目名稱:radio,代碼行數:26,代碼來源:Utils.cs

示例8: SignalAndWait

 public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext)
 {
     if ((Environment.OSInfo & Environment.OSName.Win9x) != Environment.OSName.Invalid)
     {
         throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_Win9x"));
     }
     if (toSignal == null)
     {
         throw new ArgumentNullException("toSignal");
     }
     if (toWaitOn == null)
     {
         throw new ArgumentNullException("toWaitOn");
     }
     if (-1 > millisecondsTimeout)
     {
         throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
     }
     int num = SignalAndWaitOne(toSignal.safeWaitHandle, toWaitOn.safeWaitHandle, millisecondsTimeout, toWaitOn.hasThreadAffinity, exitContext);
     if ((0x7fffffff != num) && toSignal.hasThreadAffinity)
     {
         Thread.EndCriticalRegion();
         Thread.EndThreadAffinity();
     }
     if (0x80 == num)
     {
         throw new AbandonedMutexException();
     }
     if (0x12a == num)
     {
         throw new InvalidOperationException(Environment.GetResourceString("Threading.WaitHandleTooManyPosts"));
     }
     return (num == 0);
 }
開發者ID:randomize,項目名稱:VimConfig,代碼行數:34,代碼來源:WaitHandle.cs

示例9: EndProcessing

        protected override void EndProcessing()
        {
            WaitHandle[] waitHandles = new WaitHandle[pendingResults.Count];
            for (int i = 0; i < waitHandles.Length; i++)
            {
                waitHandles[i] = pendingResults[i].AsyncWaitHandle;
            }

            WaitHandle.WaitAll(waitHandles);

            for (int i = 0; i < pendingResults.Count; i++)
            {
                try
                {
                    WriteObject(Dns.EndGetHostEntry(pendingResults[i]));
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (Exception exc)
                {
                    ErrorHandler.WriteGetHostEntryError(pendingResults[i].AsyncState.ToString(), exc);
                }
            }

            base.EndProcessing();
        }
開發者ID:nickchal,項目名稱:pash,代碼行數:28,代碼來源:ResolveHostCommand.cs

示例10: HackyComWaitOne

        /// <summary>
        /// Functionally the same as WaitOne(), but pumps com messa
        /// </summary>
        /// <param name="handle"></param>
        public static void HackyComWaitOne(WaitHandle handle)
        {
            uint nativeResult; // result of the native wait API (WaitForMultipleObjects or MsgWaitForMultipleObjectsEx)
            int managedResult; // result to return from WaitHelper

            IntPtr[] waitHandles = new IntPtr[]{
                handle.SafeWaitHandle.DangerousGetHandle() };
            uint count = 1;

            uint QS_MASK = NativeMethods.QS_ALLINPUT; // message queue status
            QS_MASK = 0; //bizhawk edit?? did we need any messages here?? apparently not???

            // the core loop
            var msg = new NativeMethods.MSG();
            while (true)
            {
                // MsgWaitForMultipleObjectsEx with MWMO_INPUTAVAILABLE returns,
                // even if there's a message already seen but not removed in the message queue
                nativeResult = NativeMethods.MsgWaitForMultipleObjectsEx(
                        count, waitHandles,
                        (uint)0xFFFFFFFF,
                        QS_MASK,
                        NativeMethods.MWMO_INPUTAVAILABLE);

                if (IsNativeWaitSuccessful(count, nativeResult, out managedResult) || WaitHandle.WaitTimeout == managedResult)
                    break;
                // there is a message, pump and dispatch it
                if (NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, NativeMethods.PM_REMOVE))
                {
                    NativeMethods.TranslateMessage(ref msg);
                    NativeMethods.DispatchMessage(ref msg);
                }
            }
            //m64pFrameComplete.WaitOne();
        }
開發者ID:cas1993per,項目名稱:bizhawk,代碼行數:39,代碼來源:Win32Hacks.cs

示例11: RegisteredWaitHandle

		internal RegisteredWaitHandle (WaitHandle waitObject, WaitOrTimerCallback callback, 
												 object cbState, int timeout, bool executeOnlyOnce)
		{
			this.waitObject = waitObject;
			this.callback = callback;
			this.cbState = cbState;
			this.timeout = timeout;
         this.executeOnlyOnce = executeOnlyOnce;

			StWaitable waitable;
			if ((waitable = waitObject.waitable) == null) {

				/*
				 * Either we're dealing with a disposed wait handle
				 * or with some other derived class.
				 */
 
				UnparkCallback (StParkStatus.Inflated);
				return;
			}

			cbparker = new CbParker (UnparkCallback, false, true);
			int ignored = 0;
         waitBlock = waitable._WaitAnyPrologue (cbparker, StParkStatus.Success, ref hint, ref ignored);

			state = ACTIVE;
         int ws = cbparker.EnableCallback (timeout);
         if (ws != StParkStatus.Pending) {
				UnparkCallback (ws);
	      }
		}
開發者ID:duarten,項目名稱:mono,代碼行數:31,代碼來源:RegisteredWaitHandle.cs

示例12: WaitAll

        public static bool WaitAll(WaitHandle[] waitHandles, int timeOutMs)
        {
            // throws an exception if there are no wait handles
            if (waitHandles == null)
                throw new ArgumentNullException(nameof(waitHandles));
            if (waitHandles.Length == 0)
                return true;

#if NETSTANDARD1_3
            return WaitHandle.WaitAll(waitHandles, timeOutMs);
#else
            if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
            {
                // WaitAll for multiple handles on an STA thread is not supported.
                // CurrentThread is ApartmentState.STA when run under unit tests
                var successfullyComplete = true;
                foreach (var waitHandle in waitHandles)
                {
                    successfullyComplete = successfullyComplete
                        && waitHandle.WaitOne(timeOutMs, false);
                }
                return successfullyComplete;
            }

            return WaitHandle.WaitAll(waitHandles, timeOutMs, false);
#endif
        }
開發者ID:AVee,項目名稱:ServiceStack,代碼行數:27,代碼來源:ActionExecExtensions.cs

示例13: SignalAndWait_MemberData

        public static IEnumerable<object[]> SignalAndWait_MemberData()
        {
            var toSignal = new WaitHandle[] { new ManualResetEvent(false), new Mutex(), new Semaphore(1, 1) };
            var toWaitOn = new AutoResetEvent(false);
            var callSignalAndWait =
                new Func<WaitHandle, WaitHandle, bool>[]
                {
                    (s, w) => WaitHandle.SignalAndWait(s, w),
                    (s, w) => WaitHandle.SignalAndWait(s, w, 0, false),
                    (s, w) => WaitHandle.SignalAndWait(s, w, TimeSpan.Zero, false),
                };

            for (int signalIndex = 0; signalIndex < toSignal.Length; ++signalIndex)
            {
                for (int callIndex = 0; callIndex < callSignalAndWait.Length; ++callIndex)
                {
                    var skipInfiniteWaitTests = callIndex == 0;
                    yield return
                        new object[]
                        {
                            toSignal[signalIndex],
                            toWaitOn,
                            callSignalAndWait[callIndex],
                            skipInfiniteWaitTests
                        };
                }
            }
        }
開發者ID:geoffkizer,項目名稱:corefx,代碼行數:28,代碼來源:WaitHandleTests.netstandard1.7.cs

示例14: TestThreading

        public void TestThreading()
        {
            try
            {
                var srids = new[] {4326, 31467, 3857, 27700};
                var precisionModels = new[]
                    {
                        new PrecisionModel(PrecisionModels.Floating), 
                        new PrecisionModel(PrecisionModels.FloatingSingle),
                        new PrecisionModel(1),
                        new PrecisionModel(10),
                        new PrecisionModel(100),
                    };

                const int numWorkItems = 30;
                var waitHandles = new WaitHandle[numWorkItems];
                for (var i = 0; i < numWorkItems; i++)
                {
                    waitHandles[i] = new AutoResetEvent(false);
                    ThreadPool.QueueUserWorkItem(TestFacories, new object[] {srids, precisionModels, waitHandles[i], i+1, false});
                }

                WaitHandle.WaitAll(waitHandles);
                Console.WriteLine("\nDone!");
                Assert.LessOrEqual(srids.Length * precisionModels.Length, ((NtsGeometryServices)GeometryServiceProvider.Instance).NumFactories,
                    "Too many factories created!");
                Assert.IsTrue(true);
            }
            catch (Exception)
            {
                Assert.IsTrue(false);
            }

        }
開發者ID:Walt-D-Cat,項目名稱:NetTopologySuite,代碼行數:34,代碼來源:GeometryServiceProviderTest.cs

示例15: Wait

		internal void Wait (object state)
		{
			bool release = false;
			try {
				_waitObject.SafeWaitHandle.DangerousAddRef (ref release);
				try {
					WaitHandle[] waits = new WaitHandle[] {_waitObject, _cancelEvent};
					do {
						int signal = WaitHandle.WaitAny (waits, _timeout, false);
						if (!_unregistered) {
							lock (this) {
								_callsInProcess++;
							}
							ThreadPool.QueueUserWorkItem (new WaitCallback (DoCallBack), (signal == WaitHandle.WaitTimeout));
						}
					} while (!_unregistered && !_executeOnlyOnce);
				} catch {
				}

				lock (this) {
					_unregistered = true;
					if (_callsInProcess == 0 && _finalEvent != null)
						NativeEventCalls.SetEvent (_finalEvent.SafeWaitHandle);
				}
			} catch (ObjectDisposedException) {
				// Can happen if we called Unregister before we had time to execute Wait
				if (release)
					throw;
			} finally {
				if (release)
					_waitObject.SafeWaitHandle.DangerousRelease ();
			}
		}
開發者ID:ItsVeryWindy,項目名稱:mono,代碼行數:33,代碼來源:RegisteredWaitHandle.cs


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