本文整理汇总了C#中ManualResetEvent.WaitOne方法的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEvent.WaitOne方法的具体用法?C# ManualResetEvent.WaitOne怎么用?C# ManualResetEvent.WaitOne使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ManualResetEvent
的用法示例。
在下文中一共展示了ManualResetEvent.WaitOne方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BlockOnSendBlockedIfReachedBoundedCapacity
public void BlockOnSendBlockedIfReachedBoundedCapacity()
{
var send1 = new ManualResetEvent(false);
var send2 = new ManualResetEvent(false);
var processor = new FakeMessageProcessor<Object>();
var bus = new OptimisticMessageSender<Object>(processor, 1);
Assert.Equal(1, bus.BoundedCapacity);
Task.Run(() =>
{
//NOTE: Once message is received for processing, the message is dequeued and thus we actually need
// one more message to confirm blocking behavior (i.e., one in queue and one being processed).
bus.Send(new Message<Object>(Guid.NewGuid(), HeaderCollection.Empty, new Object()));
bus.Send(new Message<Object>(Guid.NewGuid(), HeaderCollection.Empty, new Object()));
send1.Set();
});
Task.Run(() =>
{
send1.WaitOne();
bus.Send(new Message<Object>(Guid.NewGuid(), HeaderCollection.Empty, new Object()));
send2.Set();
});
processor.WaitForMessage();
Assert.True(send1.WaitOne(TimeSpan.FromMilliseconds(100)));
Assert.False(send2.WaitOne(TimeSpan.FromMilliseconds(100)));
processor.ProcessNextMessage();
processor.WaitForMessage();
Assert.True(send2.WaitOne(TimeSpan.FromMilliseconds(100)));
}
示例2: Main
public static int Main ()
{
var mre_l = new ManualResetEvent (false);
var mre = new ManualResetEvent (false);
Func<string, Task<string>> f = async l =>
await Task.Factory.StartNew (() => {
if (!mre_l.WaitOne (3000))
throw new ApplicationException ("3");
return l;
});
var r = f ("a");
mre_l.Set ();
if (!r.Wait (3000))
return 1;
if (r.Result != "a")
return 11;
mre_l.Reset ();
Func<Task> ff = async () =>
await Task.Factory.StartNew (() => {
if (!mre_l.WaitOne (3000))
throw new ApplicationException ("3");
});
var rr = ff ();
mre_l.Set ();
if (!rr.Wait (3000))
return 2;
Func<short, Task<short>> f2 = async l => l;
var r2 = f2 (88);
if (r2.Result != 88)
return 3;
mre.Reset ();
mre_l.Reset ();
Action a = async () => await Task.Factory.StartNew (() => {
if (!mre_l.WaitOne (3000))
throw new ApplicationException ("4");
mre.Set ();
}, CancellationToken.None);
a ();
mre_l.Set ();
if (!mre.WaitOne (3000))
return 4;
Console.WriteLine ("ok");
return 0;
}
示例3: WaitOne
public static void WaitOne()
{
ManualResetEvent h = new ManualResetEvent(true);
Assert.True(h.WaitOne());
Assert.True(h.WaitOne(1));
Assert.True(h.WaitOne(TimeSpan.FromMilliseconds(1)));
h.Reset();
Assert.False(h.WaitOne(1));
Assert.False(h.WaitOne(TimeSpan.FromMilliseconds(1)));
}
示例4: UnloadHook
static void UnloadHook (object obj, EventArgs args)
{
ManualResetEvent evt = new ManualResetEvent (false);
Console.WriteLine ("On the UnloadHook");
if (Environment.HasShutdownStarted)
throw new Exception ("Environment.HasShutdownStarted must not be true");
Action<int> f = (int x) => {
evt.WaitOne (1000);
evt.Set ();
};
f.BeginInvoke (1, null, null);
evt.WaitOne ();
Console.WriteLine ("Hook done");
}
示例5: SetReset
public void SetReset()
{
using (ManualResetEvent mre = new ManualResetEvent(false))
{
Assert.False(mre.WaitOne(0));
mre.Set();
Assert.True(mre.WaitOne(0));
Assert.True(mre.WaitOne(0));
mre.Set();
Assert.True(mre.WaitOne(0));
mre.Reset();
Assert.False(mre.WaitOne(0));
}
}
示例6: Test2
static void Test2 (Process p)
{
StringBuilder sb = new StringBuilder ();
ManualResetEvent mre_output = new ManualResetEvent (false);
p.Start ();
p.OutputDataReceived += (s, a) => {
if (a.Data == null) {
mre_output.Set ();
return;
}
sb.Append (a.Data);
};
p.BeginOutputReadLine ();
if (!p.WaitForExit (1000))
Environment.Exit (4);
if (!mre_output.WaitOne (1000))
Environment.Exit (5);
if (sb.ToString () != "hello") {
Console.WriteLine ("process output = '{0}'", sb.ToString ());
Environment.Exit (6);
}
}
示例7: 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);
}
示例8: 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 ();
}
示例9: 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);
}
示例10: 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);
}
示例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;
}
示例12: 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());
}
示例13: Main
public static int Main ()
{
var mre = new ManualResetEvent (false);
await_mre = new ManualResetEvent (false);
var context = new MyContext (mre);
try {
SynchronizationContext.SetSynchronizationContext (context);
var t = Test ();
await_mre.Set ();
if (!t.Wait (3000))
return 3;
// Wait is needed because synchronization is executed as continuation (once task finished)
if (!mre.WaitOne (3000))
return 2;
} finally {
SynchronizationContext.SetSynchronizationContext (null);
}
if (context.Started != 0 || context.Completed != 0 || context.SendCounter != 0)
return 1;
Console.WriteLine ("ok");
return 0;
}
示例14: Run
//public Run()
public void Run()
{/*{{{*/
allDone = new ManualResetEvent(false);
// Create an instance of the RequestState class.
RequestState myRequestState = new RequestState();
// Begin an asynchronous request for information like host name, IP addresses, or
// aliases for specified the specified URI.
IAsyncResult asyncResult = Dns.BeginGetHostEntry("www.contiioso.com", new AsyncCallback(RespCallback), myRequestState );
// Wait until asynchronous call completes.
allDone.WaitOne();
//asyncResult.AsyncWaitHandle.WaitOne();
if(myRequestState.host == null) return;
if(asyncResult.IsCompleted) Console.WriteLine("Get IPs!!");
Console.WriteLine("Host name : " + myRequestState.host.HostName);
Console.WriteLine("\nIP address list : ");
for(int index=0; index < myRequestState.host.AddressList.Length; index++)
{
Console.WriteLine(myRequestState.host.AddressList[index]);
}
Console.WriteLine("\nAliases : ");
for(int index=0; index < myRequestState.host.Aliases.Length; index++)
{
Console.WriteLine(myRequestState.host.Aliases[index]);
}
}/*}}}*/
示例15: 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;
}