Skip to content

Instantly share code, notes, and snippets.

@esdrubal
Created August 6, 2014 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esdrubal/01969cb78601f3e8d965 to your computer and use it in GitHub Desktop.
Save esdrubal/01969cb78601f3e8d965 to your computer and use it in GitHub Desktop.
AutoResetEvent
using System.IO;
using System.Text;
using System.Threading;
using System.Net;
using System;
class Program
{
private static AutoResetEvent autoEvent = new AutoResetEvent(false);
private static AutoResetEvent autoEvent2 = new AutoResetEvent(false);
public static void Main()
{
HttpListener listener = new HttpListener();
var url = "http://localhost:2999/";
listener.Prefixes.Add(url);
listener.Start();
Console.WriteLine("Listening...");
for (var i = 0; i < 20; i++)
CreateListenerRequest (listener, url);
Console.ReadLine();
}
public static void CreateListenerRequest (HttpListener listener, string uri)
{
Console.WriteLine("BeginGetContext...");
var asyncResult = listener.BeginGetContext (ListenerCallback, listener);
var request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
using (var writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
writer.Write ("request");
// send request
var response = request.GetResponse ();
response.Close ();
asyncResult.AsyncWaitHandle.WaitOne();
}
public static void ListenerCallback(IAsyncResult result)
{
Console.WriteLine("ListenerCallback...");
autoEvent.Set();
//Thread.Sleep(10);
autoEvent.Reset();
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
context.Request.InputStream.Close ();
context.Response.OutputStream.Close();
int res = WaitHandleNext();
if (res == 0 || res == 1)
{
// Never get this line
Console.WriteLine("Done...");
}
else if (res == WaitHandle.WaitTimeout)
{
// Always here
Console.WriteLine("Done by timeout");
}
}
private static int WaitHandleNext()
{
Console.WriteLine("WaitHandleNext...");
int waitResult = WaitHandle.WaitAny(new[] { autoEvent, autoEvent2 },
TimeSpan.FromSeconds(30), false);
return waitResult;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment