static void DoPollingVariant() { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(HttpContext.Current.Session, HttpContext.Current.Trace); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); // Poll while simulating work. while (result.IsCompleted == false) { Thread.Sleep(250); Console.Write("."); } // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); }
static void DoCallbackVariant() { // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(HttpContext.Current.Session, HttpContext.Current.Trace); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // The threadId parameter of TestMethod is an out parameter, so // its input value is never used by TestMethod. Therefore, a dummy // variable can be passed to the BeginInvoke call. If the threadId // parameter were a ref parameter, it would have to be a class- // level field so that it could be passed to both BeginInvoke and // EndInvoke. int dummy = 0; // Initiate the asynchronous call, passing three seconds (3000 ms) // for the callDuration parameter of TestMethod; a dummy variable // for the out parameter (threadId); the callback delegate; and // state information that can be retrieved by the callback method. // In this case, the state information is a string that can be used // to format a console message. IAsyncResult result = caller.BeginInvoke(3000, out dummy, new AsyncCallback(CallbackMethod), "The call executed on thread {0}, with return value \"{1}\"."); Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId); // The callback is made on a ThreadPool thread. ThreadPool threads // are background threads, which do not keep the application running // if the main thread ends. Comment out the next line to demonstrate // this. Thread.Sleep(4000); Console.WriteLine("The main thread ends."); }
static void DoWaitHandleVariant() { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(HttpContext.Current.Session, HttpContext.Current.Trace); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); // Perform additional processing here. // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); // Close the wait handle. result.AsyncWaitHandle.Close(); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); }
/// <summary> /// Waiting for an Asynchronous Call with EndInvoke. /// </summary> public static void Main() { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(HttpContext.Current.Session, HttpContext.Current.Trace); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Call EndInvoke to wait for the asynchronous call to complete, // and to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); }
/// <summary> /// Main: Async operation beginning using WaitOne (waithandler) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <param name="cb"></param> /// <param name="state"></param> /// <returns></returns> IAsyncResult BeginAsyncOperation(object sender,EventArgs e,AsyncCallback cb,object state) { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000, out threadId, //null, null); new AsyncCallback(EndAsyncOperation), "The call executed on thread {0}, with return value \"{1}\"."); Trace.Write("BeginAsyncOperation", string.Format("Waiting for the WaitHandle to become signaled...\nThreadId={0} \tResultState = {1}\t Caller= {2}) ", threadId, result.AsyncState, caller)); result.AsyncWaitHandle.WaitOne(); // Perform additional processing here. // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); Queue<int> threadIds = m_TaskIds;// Session["TaskIds"] as Queue<int>; if (threadIds != null) threadIds.Enqueue(threadId); IDictionary<int, IAsyncResult> asyncResult = m_AsyncResults;// Session["AsyncResults"] as Dictionary<int, IAsyncResult>; if (asyncResult != null) asyncResult.Add(new KeyValuePair<int, IAsyncResult>(threadId, result)); IDictionary<int, AsyncMethodCaller> asyncCallers = m_AsyncCallers;// Session["AsyncCallers"] as Dictionary<int, AsyncMethodCaller>; if (asyncCallers != null) asyncCallers.Add(new KeyValuePair<int, AsyncMethodCaller>(threadId, caller)); // Close the wait handle. result.AsyncWaitHandle.Close(); return result; }
private void DoTestAsyncOperation() { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(HttpContext.Current.Session, HttpContext.Current.Trace); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(1000, out threadId, null, null); result.AsyncWaitHandle.WaitOne(); Trace.Write("BeginAsyncOperation", string.Format("Waiting for the WaitHandle to become signaled...\nThreadId={0} \tResultState = {1}\t Caller= {2}", threadId, result.AsyncState, caller)); // Perform additional processing here. // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); Queue<int> threadIds = m_TaskIds;// Session["TaskIds"] as Queue<int>; if (threadIds != null) threadIds.Enqueue(threadId); if (m_AsyncResults != null) m_AsyncResults.Add(threadId, result); // Close the wait handle. result.AsyncWaitHandle.Close(); }
void Page_Load(object sender, EventArgs e) { m_TaskIds = new Queue<int>(); m_AsyncResults = new Dictionary<int, IAsyncResult>(); m_AsyncCallbacks = new Dictionary<int, AsyncCallback>(); if (!IsPostBack) { m_MessageQ = new Queue<string>(); Session["ObserverNotified"] = new Queue<string>();//Cross-process? Session["ObserverNotified-Stacked"] = new Stack<string>();//Cross-process? Session["TotalJobQueue"] = new Queue<string>(); Session["countMaxNotification"] = 0; Session["countMaxNotifications"] = 0; Session["TaskQ-Empty"] = true; //init } if (IsAsync) { m_Subject = new SubjectImpl(); m_Subject.Message = new TextBox(); m_Observer = new Observer(m_Subject); // Create an instance of the test class. m_Producer = new AsyncDemo(HttpContext.Current.Session, HttpContext.Current.Trace); m_Producer.NotifyLogger += m_Observer.UpdateLog; m_Producer.AsyncNotificationEvent += ObserverNotified; m_Producer.Attach(); Label1.Text = "Page_Load: thread #" + System.Threading.Thread.CurrentThread.GetHashCode(); BeginEventHandler bh = new BeginEventHandler(this.BeginGetAsyncData); EndEventHandler eh = new EndEventHandler(this.EndGetAsyncData); AddOnPreRenderCompleteAsync(bh, eh); // Initialize the WebRequest. string address = "http://localhost/"; m_MyRequest = System.Net.WebRequest.Create(address); } }