当前位置: 首页>>代码示例>>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;未经允许,请勿转载。