//Method2: asynchronous pattern using a BeginInvoke, followed by waiting with a time-out public void GetResultsAndWait(string key, ref List <string> keys_matched, int waitTime = 10000) { //declare instance of delegate GetResultsDelegate getResultDelegate = new GetResultsDelegate(ResultsGetter.GetResults); //asynchonously invoke the GetResult method IAsyncResult result = getResultDelegate.BeginInvoke(key, ref keys_matched, null, null); while (!result.IsCompleted) { //do any work that can done before waiting result.AsyncWaitHandle.WaitOne(waitTime, false); } result.AsyncWaitHandle.Close(); //the asynchronous operation has completed bool return_val = getResultDelegate.EndInvoke(ref keys_matched, result); }
//Method1: asynchronous pattern using a callback method public void GetResultUsingCallback(string key, ref List <string> keys_matched) { //declare instance of delegate GetResultsDelegate getResultDelegte = new GetResultsDelegate(ResultsGetter.GetResults); // Waiter will keep the main application thread from // ending before the callback completes because // the main thread blocks until the waiter is signaled // in the callback waiter = new ManualResetEvent(false); //define the AsyncCallback delegate AsyncCallback callback = new AsyncCallback(this.ResultsReady); // Asynchronously invoke the GetRsults method IAsyncResult result = getResultDelegte.BeginInvoke(key, ref keys_matched, callback, key); // Do some other useful work while // waiting for the asynchronous operation to complete. // When no more work can be done, wait. waiter.WaitOne(); }