本文整理汇总了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);
}
}
}
示例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);
}
示例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
}
}
示例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();
}
示例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;
}
}
示例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;
}
}
示例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);
}
示例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);
}
示例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();
}
示例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();
}
示例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);
}
}
示例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
}
示例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
};
}
}
}
示例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);
}
}
示例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 ();
}
}