private void SshExpectAsyncCallback(IAsyncResult r) { ExpectAsyncResult ear = r as ExpectAsyncResult; KeyValuePair <string, Stopwatch> cas = (KeyValuePair <string, Stopwatch>)r.AsyncState; if (r.IsCompleted) { cas.Value.Stop(); Debug("Completed expect operation {0} in {1} ms.", cas.Key, cas.Value.ElapsedMilliseconds); } }
/// <summary> /// Begins the expect. /// </summary> /// <param name="timeout">The timeout.</param> /// <param name="callback">The callback.</param> /// <param name="state">The state.</param> /// <param name="expectActions">The expect actions.</param> /// <returns> /// An <see cref="IAsyncResult" /> that references the asynchronous operation. /// </returns> public IAsyncResult BeginExpect(TimeSpan timeout, AsyncCallback callback, object state, params ExpectAction[] expectActions) { var text = string.Empty; // Create new AsyncResult object var asyncResult = new ExpectAsyncResult(callback, state); // Execute callback on different thread ThreadAbstraction.ExecuteThread(() => { string expectActionResult = null; try { do { lock (_incoming) { if (_incoming.Count > 0) { text = _encoding.GetString(_incoming.ToArray(), 0, _incoming.Count); } if (text.Length > 0) { foreach (var expectAction in expectActions) { var match = expectAction.Expect.Match(text); if (match.Success) { var result = text.Substring(0, match.Index + match.Length); for (var i = 0; i < match.Index + match.Length && _incoming.Count > 0; i++) { // Remove processed items from the queue _incoming.Dequeue(); } expectAction.Action(result); if (callback != null) { callback(asyncResult); } expectActionResult = result; } } } } if (expectActionResult != null) break; if (timeout.Ticks > 0) { if (!_dataReceived.WaitOne(timeout)) { if (callback != null) { callback(asyncResult); } break; } } else { _dataReceived.WaitOne(); } } while (true); asyncResult.SetAsCompleted(expectActionResult, true); } catch (Exception exp) { asyncResult.SetAsCompleted(exp, true); } }); return asyncResult; }