本文整理汇总了C#中ManualResetEvent类的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEvent类的具体用法?C# ManualResetEvent怎么用?C# ManualResetEvent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ManualResetEvent类属于命名空间,在下文中一共展示了ManualResetEvent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例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);
}
示例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);
}
示例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);
}
示例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...");
}
示例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 ();
}
示例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;
}
示例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);
}
示例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);
}
示例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 );
}
}
示例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: 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);
}
示例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());
}
示例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);
}
示例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");
}
}