public string ReadLine(int timeoutms) { try { ReadLineDelegate d = Console.ReadLine; IAsyncResult result = d.BeginInvoke(null, null); result.AsyncWaitHandle.WaitOne(timeoutms);//timeout e.g. 15000 for 15 secs if (result.IsCompleted) { string resultstr = d.EndInvoke(result); //Console.WriteLine("Read: " + resultstr); return(resultstr); } else { return(""); } } catch (Exception ex) { LogHandler logHandler = new LogHandler(); logHandler.LogWarning("ERROR in ReadLine " + ex.Message + "\n" + ex.InnerException.ToString()); return(""); } }
public string GetActivePorts() { try { Process prc = new Process(); StreamWriter sw; StreamReader sr; prc.StartInfo.FileName = "cmd.exe"; prc.StartInfo.UseShellExecute = false; prc.StartInfo.RedirectStandardOutput = true; prc.StartInfo.RedirectStandardInput = true; prc.StartInfo.CreateNoWindow = true; prc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; prc.Start(); sw = prc.StandardInput; sr = prc.StandardOutput; sw.Write("netstat -a -n -o" + Environment.NewLine); strActivePort = string.Empty; string line; ReadLineDelegate rl = new ReadLineDelegate(sr.ReadLine); while (true) { IAsyncResult ares = rl.BeginInvoke(null, null); if (ares.AsyncWaitHandle.WaitOne(500) == false) { break; } line = rl.EndInvoke(ares); if (line != null) { strActivePort += line + Environment.NewLine; } } strActivePort = strActivePort.Substring(strActivePort.IndexOf("PID") + 3); } catch (Exception ex) { } return(strActivePort); }
public static string ReadLineWithTimeout(int timeoutms = 5000) { ReadLineDelegate d = Console.ReadLine; IAsyncResult result = d.BeginInvoke(null, null); result.AsyncWaitHandle.WaitOne(timeoutms); //timeout e.g. 15000 for 15 secs if (result.IsCompleted) { string resultstr = d.EndInvoke(result); return(resultstr); } else { throw new TimeoutException("Timed Out!"); } }
private static string ReadLine(int timeoutms) { Logger.Info("Done! Waiting for next run. Enter Q to quit or wait " + timeoutms / 1000 + " seconds and the process will continue..."); ReadLineDelegate d = Console.ReadLine; var result = d.BeginInvoke(null, null); result.AsyncWaitHandle.WaitOne(timeoutms); //timeout e.g. 15000 for 15 secs if (result.IsCompleted) { return(d.EndInvoke(result)); } return(""); }
private static string ReadLine(int timeoutms) { System.Console.WriteLine("Wait Input"); ReadLineDelegate d = System.Console.ReadLine; IAsyncResult result = d.BeginInvoke(null, null); result.AsyncWaitHandle.WaitOne(timeoutms);//timeout e.g. 15000 for 15 secs if (result.IsCompleted) { string resultstr = d.EndInvoke(result); System.Console.WriteLine("Read: " + resultstr); return(resultstr); } else { System.Console.WriteLine("Timed out!"); //throw new TimedoutException("Timed Out!"); return(null); } }
/// <summary> /// http://stackoverflow.com/questions/57615/how-to-add-a-timeout-to-console-readline /// </summary> /// <param name="secTimeOut"></param> /// <param name="default"></param> /// <returns></returns> public static string ReadLine(int secTimeOut, string @default) { ReadLineDelegate d = Console.ReadLine; IAsyncResult result = d.BeginInvoke(null, null); result.AsyncWaitHandle.WaitOne(secTimeOut * 1000); // timeout e.g. 15000 for 15 secs if (result.IsCompleted) { string resultstr = d.EndInvoke(result); //Console.WriteLine("Read: " + resultstr); return(resultstr); } else { //Console.WriteLine("Timed out!"); //throw new TimedoutException("Timed Out!"); return(@default); } }
public string GetResponse() { try { data = string.Empty; string line; int sleep; if (firstrun) { sleep = 400; } else { sleep = 100; } ReadLineDelegate rl = new ReadLineDelegate(stdout.ReadLine); while (true) { IAsyncResult ares = rl.BeginInvoke(null, null); if (ares.AsyncWaitHandle.WaitOne(sleep) == false) { break; } line = rl.EndInvoke(ares); if (line != null) { data += line + Environment.NewLine; } } } catch (Exception ex) { } return(data); }
public void ProcessQueue(object ThreadId) { string strThreadId = string.Format("{0:D2}", int.Parse(ThreadId.ToString())); Board board = new Board(); WaitForReady(); bool bExitAfterEmptyQueue; if (!Boolean.TryParse(ConfigurationManager.AppSettings["ExitAfterEmptyQueue"], out bExitAfterEmptyQueue)) { bExitAfterEmptyQueue = false; } bool bExitAfterResume; if (!Boolean.TryParse(ConfigurationManager.AppSettings["ExitAfterResume"], out bExitAfterResume)) { bExitAfterResume = true; } while (!Program.bClosing) { try { bool bResuming = false; if (!File.Exists("last" + strThreadId + ".txt")) { Console.WriteLine("[" + strThreadId + "] 正在获取新队列..."); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["CloudBookURL"] + "?action=getqueue&token=" + ConfigurationManager.AppSettings["AccessToken"]); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("获取队列失败。"); } StreamReader myStreamReader = new StreamReader(response.GetResponseStream()); String result = TrimFromZero(myStreamReader.ReadToEnd()); myStreamReader.Close(); response.Close(); if (result.Length > 0) { if (result == "tokenerror") { throw new Exception("AccessToken错误。"); } File.WriteAllText("last" + strThreadId + ".txt", result); } else if (bExitAfterEmptyQueue) { Program.bClosing = true; return; } } } else { Console.WriteLine("[" + strThreadId + "] 正在恢复队列..."); if (bExitAfterResume) { bResuming = true; } } if (File.Exists("last" + strThreadId + ".txt")) { String fenkey = File.ReadAllText("last" + strThreadId + ".txt"); StringReader sr = new StringReader(fenkey); String fen = TrimFromZero(sr.ReadLine()); while (fen != null && fen.Length > 0) { Console.WriteLine("[" + strThreadId + "] 正在计算..."); String[] outdata = fen.Split(' '); board.init(outdata[0] + ' ' + outdata[1]); if (outdata.Length > 2) { board.makemove(outdata[3]); } EngineStreamWriter.WriteLine("fen " + board.getfen()); EngineStreamWriter.WriteLine(ConfigurationManager.AppSettings["GoCommand"]); String outstr = EngineStreamReader.ReadLine(); bool hasBestMove = false; int score = int.MinValue; int nps = 0; long nodes = 0; String bestmove = null; while (outstr != null) { var tmp = outstr.Split(' '); for (int i = 0; i < tmp.Length; i++) { if (tmp[i] == "bestmove") { hasBestMove = true; bestmove = tmp[i + 1]; if (bestmove == "(none)") { score = 0; } break; } else if (tmp[i] == "score") { try { score = int.Parse(tmp[i + 1]); } catch { } } else if (tmp[i] == "nps") { try { nps = int.Parse(tmp[i + 1]) / 1000; } catch { } } else if (tmp[i] == "nodes") { try { nodes = int.Parse(tmp[i + 1]) / 1000; } catch { } } } if (hasBestMove) { break; } ReadLineDelegate d = EngineStreamReader.ReadLine; IAsyncResult result = d.BeginInvoke(null, null); while (true) { result.AsyncWaitHandle.WaitOne(300000); if (result.IsCompleted) { outstr = d.EndInvoke(result); break; } else { EngineStreamWriter.WriteLine("stop"); } } } WaitForReady(); if (hasBestMove && score != int.MinValue) { if (Math.Abs(score) > 30000) { Console.WriteLine("[" + strThreadId + "] 清除Hash重新计算..."); EngineStreamWriter.WriteLine("ucinewgame"); WaitForReady(); continue; } Console.WriteLine("[" + strThreadId + "] 正在提交结果...(NPS = " + nps.ToString() + "K)"); bool succeess = false; while (!succeess) { if (outdata.Length > 2) { try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["CloudBookURL"] + "?action=store&board=" + outdata[0] + ' ' + outdata[1] + "&move=" + outdata[3] + "&score=" + score.ToString() + "&nodes=" + nodes.ToString() + "&token=" + StringToMD5Hash(ConfigurationManager.AppSettings["AccessToken"] + outdata[0] + ' ' + outdata[1] + outdata[3] + score.ToString())); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("提交结果失败。"); } StreamReader myStreamReader = new StreamReader(response.GetResponseStream()); String result = TrimFromZero(myStreamReader.ReadToEnd()); myStreamReader.Close(); response.Close(); if (result == "tokenerror") { throw new Exception("AccessToken错误。"); } } board.init(outdata[0] + ' ' + outdata[1]); board.makemove(outdata[3]); int tmpscore = -score; if (tmpscore < -10000) { tmpscore--; } else if (tmpscore > 10000) { tmpscore++; } req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["CloudBookURL"] + "?action=store&board=" + board.getfen() + "&move=" + bestmove + "&score=" + tmpscore.ToString() + "&token=" + StringToMD5Hash(ConfigurationManager.AppSettings["AccessToken"] + board.getfen() + bestmove + tmpscore.ToString())); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("提交结果失败。"); } StreamReader myStreamReader = new StreamReader(response.GetResponseStream()); String result = TrimFromZero(myStreamReader.ReadToEnd()); myStreamReader.Close(); response.Close(); if (result == "tokenerror") { throw new Exception("AccessToken错误。"); } } succeess = true; } catch (Exception e) { Console.WriteLine(e.ToString()); Thread.Sleep(1000); } } else { try { int tmpscore = -score; if (tmpscore < -10000) { tmpscore--; } else if (tmpscore > 10000) { tmpscore++; } HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["CloudBookURL"] + "?action=store&board=" + outdata[0] + ' ' + outdata[1] + "&move=" + bestmove + "&score=" + tmpscore.ToString() + "&nodes=" + nodes.ToString() + "&token=" + StringToMD5Hash(ConfigurationManager.AppSettings["AccessToken"] + outdata[0] + ' ' + outdata[1] + bestmove + tmpscore.ToString())); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("提交结果失败。"); } StreamReader myStreamReader = new StreamReader(response.GetResponseStream()); String result = TrimFromZero(myStreamReader.ReadToEnd()); myStreamReader.Close(); response.Close(); if (result == "tokenerror") { throw new Exception("AccessToken错误。"); } } succeess = true; } catch (Exception e) { Console.WriteLine(e.ToString()); Thread.Sleep(1000); } } } } fen = TrimFromZero(sr.ReadLine()); } fenkey = StringToMD5Hash(fenkey); try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["CloudBookURL"] + "?action=ackqueue&key=" + fenkey + "&token=" + StringToMD5Hash(ConfigurationManager.AppSettings["AccessToken"] + fenkey)); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("提交结果失败。"); } StreamReader myStreamReader = new StreamReader(response.GetResponseStream()); String result = TrimFromZero(myStreamReader.ReadToEnd()); myStreamReader.Close(); response.Close(); if (result == "tokenerror") { throw new Exception("AccessToken错误。"); } } } catch (Exception e) { Console.WriteLine(e.ToString()); Thread.Sleep(1000); } File.Delete("last" + strThreadId + ".txt"); if (bResuming) { Program.bClosing = true; return; } } else { Thread.Sleep(3000); } } catch (Exception e) { Console.WriteLine(e.ToString()); Thread.Sleep(1000); } } StopEngine(); }
/// <summary> /// Consoles the read input. /// </summary> public static void ConsoleReadInput() { // listen for 'Q' to quit application. had to do this to make it work through psexec i // could not get ctrl-c to pass while in psexec only Console.readline works in psexec Thread.CurrentThread.Name = "_consoleReader"; string resultstr = string.Empty; ReadLineDelegate d = Console.Read; IAsyncResult result = d.BeginInvoke(null, null); while (true) { try { if (CDFMonitor.CloseCurrentSessionEvent.WaitOne(100)) { Debug.Print("exiting console reader"); return; } result.AsyncWaitHandle.WaitOne(1000); if (result.IsCompleted) { resultstr = Convert.ToString(Convert.ToChar(d.EndInvoke(result))); switch (resultstr.ToUpper()) { case "Q": CDFMonitor.CloseCurrentSessionEvent.Set(); return; case "C": // clear console output Console.Clear(); break; case "M": CDFMonitor.LogOutputHandler(string.Format("CDFMarker:{0}:{1}", CDFMonitor.Instance.MarkerEvents, CDFMonitor.Instance.MarkerEvents++), JobOutputType.Etw); break; case "S": // Show stats Console.Clear(); while (true) { if (CDFMonitor.CloseCurrentSessionEvent.WaitOne(200)) { return; } // Console.Clear(); Console.SetCursorPosition(0, 0); int count = 0; foreach ( string s in CDFMonitor.Instance.GetStats().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) { string newString = s; while (Console.BufferWidth - 1 > newString.Length) { newString += " "; } if (++count == Console.WindowHeight - 2) { break; } Console.WriteLine(newString); } } default: break; } // restart result = d.BeginInvoke(null, null); } else { continue; } } catch (Exception e) { // dont writeoutput as ctrl-c will throw exception Debug.Print("Fail:ConsoleReadInput exception: " + e.ToString()); return; } } }
public string GetResponse() { try { data = string.Empty; string line; int sleep; if (firstrun) { sleep = 400; } else { sleep = 100; } ReadLineDelegate rl = new ReadLineDelegate(stdout.ReadLine); while (true) { IAsyncResult ares = rl.BeginInvoke(null, null); if (ares.AsyncWaitHandle.WaitOne(sleep) == false) { break; } line = rl.EndInvoke(ares); if (line != null) { data += line + Environment.NewLine; } } } catch (Exception ex) { } return data; }