本文整理汇总了C#中AutoResetEvent类的典型用法代码示例。如果您正苦于以下问题:C# AutoResetEvent类的具体用法?C# AutoResetEvent怎么用?C# AutoResetEvent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AutoResetEvent类属于命名空间,在下文中一共展示了AutoResetEvent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestWaitOneMultiThreaded
public void TestWaitOneMultiThreaded()
{
bool x;
Thread thread1;
if (!TestThread.IsThreadingSupported)
{
return;
}
e1 = new AutoResetEvent(false);
x = e1.WaitOne(10,false);
AssertEquals("WaitOne(unset)", x, false);
thread1 = new Thread(new ThreadStart(SetE1));
thread1.Start();
x = e1.WaitOne(4000, false);
AssertEquals("WaitOne(set)", x, true);
// It should be reset now.
x = e1.WaitOne(10, false);
AssertEquals("WaitOne(set)", x, false);
}
示例2: Main
static int Main ()
{
receivedMsg = new AutoResetEvent (false);
HttpChannel channel = new HttpChannel (0);
#if NET_2_0
ChannelServices.RegisterChannel (channel, false);
#else
ChannelServices.RegisterChannel (channel);
#endif
ServerTalk _ServerTalk = (ServerTalk) Activator.GetObject (typeof (ServerTalk), "http://localhost:8081/hydraplus.soap");
CallbackSink _CallbackSink = new CallbackSink ();
_CallbackSink.OnHostToClient += new delCommsInfo (CallbackSink_OnHostToClient);
_ServerTalk.RegisterHostToClient ("Me", 0, new delCommsInfo (_CallbackSink.HandleToClient));
string messageSent = Guid.NewGuid ().ToString ();
_ServerTalk.SendMessageToServer (new CommsInfo ("Me", "txt", messageSent));
if (receivedMsg.WaitOne (5000, false)) {
Assert.AreEqual (messageReceived, messageSent, "#1");
return 0;
} else {
return 1;
}
}
示例3: DownloadWebpage
private void DownloadWebpage()
{
string URL = TextBox1.Text;
AutoResetEvent resultEvent = new AutoResetEvent(false);
string result = null;
bool visible = this.Checkbox1.Checked;
IEBrowser browser = new IEBrowser(visible, URL, resultEvent);
// wait for the third thread getting result and setting result event
EventWaitHandle.WaitAll(new AutoResetEvent[] { resultEvent });
// the result is ready later than the result event setting sometimes
while (browser == null || browser.HtmlResult == null) Thread.Sleep(5);
result = browser.HtmlResult;
if (!visible) browser.Dispose();
//把获取的html内容通过label显示出来
Label2.Text = result;
//保存结果到本程序的目录中
string path = Request.PhysicalApplicationPath;
TextWriter tw = new StreamWriter(path + @"softlab/result.html");
tw.Write(result);
tw.Close();
//open a new web page to display result got from webbrowser.
Response.Output.WriteLine("<script>window.open ('result.html','mywindow','location=1,status=0,scrollbars=1,resizable=1,width=600,height=600');</script>");
}
示例4: Main
static void Main()
{
// Create an event to signal the timeout count threshold in the
// timer callback.
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10);
// Create an inferred delegate that invokes methods for the timer.
TimerCallback tcb = statusChecker.CheckStatus;
// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);
// When autoEvent signals, change the period to every
// 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period.\n");
// When autoEvent signals the second time, dispose of
// the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
示例5: 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 );
}
}
示例6: PosTest1
public bool PosTest1()
{
bool retVal = true;
AutoResetEvent are;
TestLibrary.TestFramework.BeginScenario("PosTest1: AutoResetEvent.Set()");
try
{
// false means that the initial state should be not signaled
are = new AutoResetEvent(false);
// set the signal
if (!are.Set())
{
TestLibrary.TestFramework.LogError("001", "AutoResetEvent.Set() failed");
retVal = false;
}
// verify that the autoreset event is signaled
// if it is not signaled the following call will block for ever
TestLibrary.TestFramework.LogInformation("Calling AutoResetEvent.WaitOne()... if the event is not signaled it will hang");
are.WaitOne();
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
示例7: Run
public int Run()
{
AutoResetEvent are = new AutoResetEvent(true);
Stopwatch sw = new Stopwatch();
if(!are.WaitOne(0))//,false))
{
Console.WriteLine("Signalled event should always return true on call to !are.WaitOne(0,false).");
return -3;
}
sw.Start();
bool ret = are.WaitOne(1000);//,false);
sw.Stop();
//We should never get signaled
if(ret)
{
Console.WriteLine("AutoResetEvent should never be signalled.");
return -1;
}
if(sw.ElapsedMilliseconds < 900)
{
Console.WriteLine("It should take at least 900 milliseconds to call bool ret = are.WaitOne(1000,false);.");
Console.WriteLine("sw.ElapsedMilliseconds = " + sw.ElapsedMilliseconds);
return -2;
}
return 100;
}
示例8: Main
public static int Main(String[] args)
{
Console.WriteLine("MutexSample.cs ...");
gM1 = new Mutex(true,"MyMutex");
gM2 = new Mutex(true);
Console.WriteLine(" - Main Owns gM1 and gM2");
AutoResetEvent[] evs = new AutoResetEvent[4];
evs[0] = Event1;
evs[1] = Event2;
evs[2] = Event3;
evs[3] = Event4;
MutexSample tm = new MutexSample( );
Thread t1 = new Thread(new ThreadStart(tm.t1Start));
Thread t2 = new Thread(new ThreadStart(tm.t2Start));
Thread t3 = new Thread(new ThreadStart(tm.t3Start));
Thread t4 = new Thread(new ThreadStart(tm.t4Start));
t1.Start( );
t2.Start( );
t3.Start( );
t4.Start( );
Thread.Sleep(2000);
Console.WriteLine(" - Main releases gM1");
gM1.ReleaseMutex( );
Thread.Sleep(1000);
Console.WriteLine(" - Main releases gM2");
gM2.ReleaseMutex( );
WaitHandle.WaitAll(evs);
Console.WriteLine("... MutexSample.cs");
return 0;
}
示例9: Main
public static void Main()
{
e = new AutoResetEvent(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...");
}
示例10: Main
public static void Main()
{
AutoResetEvent auto = new AutoResetEvent(true);
bool state = auto.WaitOne(5000, true);
Console.WriteLine("After Frist Wait : " + state);
state = auto.WaitOne(10000, true);
Console.WriteLine("After Second Wait : " + state);
}
示例11: Ctor
public void Ctor()
{
using (AutoResetEvent are = new AutoResetEvent(false))
Assert.False(are.WaitOne(0));
using (AutoResetEvent are = new AutoResetEvent(true))
Assert.True(are.WaitOne(0));
}
示例12: Main
static int Main ()
{
SoapServerFormatterSinkProvider serverFormatter = new SoapServerFormatterSinkProvider ();
serverFormatter.TypeFilterLevel = TypeFilterLevel.Full;
Hashtable ht = new Hashtable ();
ht ["name"] = "hydraplus";
ht ["port"] = 8081;
ht ["authorizedGroup"] = "everyone";
HttpChannel channel = new HttpChannel (ht, null, serverFormatter);
#if NET_2_0
ChannelServices.RegisterChannel (channel, false);
#else
ChannelServices.RegisterChannel (channel);
#endif
WellKnownServiceTypeEntry entry = new WellKnownServiceTypeEntry (
typeof (ServerTalk), "hydraplus.soap",
WellKnownObjectMode.Singleton);
RemotingConfiguration.RegisterWellKnownServiceType (entry);
ServerTalk.NewUser = new delUserInfo (NewClient);
ServerTalk.DelUser = new delRemoveUser (RemoveClient);
ServerTalk.ClientToHost = new delCommsInfo (ClientToHost);
clientConnected = new AutoResetEvent (false);
clientDisconnected = new AutoResetEvent (false);
// wait for client to connect
if (!clientConnected.WaitOne (20000, false)) {
ReportFailure ("No client connected in time.");
return 1;
}
// wait for message to arrive
while (true) {
Thread.Sleep (50);
if (ServerTalk.ClientToServerQueue.Count > 0) {
CommsInfo info = (CommsInfo) ServerTalk.ClientToServerQueue.Dequeue ();
ClientToHost (info);
break;
}
}
// send message to client
ServerTalk.RaiseHostToClient (client.Id, "txt", receivedMsg);
// wait for client to disconnect
if (clientConnected.WaitOne (2000, false)) {
ReportFailure ("Client did not disconnect in time.");
return 2;
}
return 0;
}
示例13: HandleCharacter
private static void HandleCharacter(Match match, HttpListenerResponse response)
{
// here we are running in a thread different from the main thread
int pid = Convert.ToInt32(match.Groups[1].Value);
string responseString = "";
// event used to wait the answer from the main thread.
AutoResetEvent autoEvent = new AutoResetEvent(false);
// var to store the character we are looking for
Character character = null;
// this bool is to check character is valid ... explanation below
bool found = false;
// we queue an 'action' to be executed in the main thread
MainGameObject.QueueOnMainThread(()=>{
// here we are in the main thread (see Update() in MainGameObject.cs)
// retrieve the character
character = MainGameObject.Instance().CharacterByID(pid);
// if the character is null set found to false
// have to do this because cannot call "character==null" elsewhere than the main thread
// do not know why (yet?)
// so if found this "trick"
found = (character!=null?true:false);
// set the event to "unlock" the thread
autoEvent.Set();
});
// wait for the end of the 'action' executed in the main thread
autoEvent.WaitOne();
// generate the HTTP answer
if (found==false) {
responseString = "<html><body>character: not found (" + pid + ")</body></html>";
} else {
responseString = "<html><body>";
responseString += "<img src='data:image/jpg;base64," + character.imageB64 + "'></img></br>";
responseString += "name: " + character.name + "</br>";
responseString += "life: " + character.life + "</br>";
responseString += "streght " + character.streght + "</br>";
responseString += "dexterity " + character.dexterity + "</br>";
responseString += "consitution " + character.consitution + "</br>";
responseString += "intelligence " + character.intelligence + "</br>";
responseString += "</body></html>";
}
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
}
示例14: SetWaitHandle_Enqueue_Asynchronous
public void SetWaitHandle_Enqueue_Asynchronous()
{
using (AutoResetEvent waitHandle = new AutoResetEvent(false))
{
this.q = new EventQueue();
this.q.SetWaitHandleForSynchronizedEvents(waitHandle);
this.afterEnqueue = false;
this.RunProducerConsumer();
}
}
示例15: Main
static int Main ()
{
for (int i = 0; i < Count; i++) {
events [i] = new AutoResetEvent (false);
ThreadPool.QueueUserWorkItem (new WaitCallback (Callback), i);
}
AutoResetEvent.WaitAll (events);
return exit_code;
}