/// <summary> /// Creates new instance of <see cref="BackgroundStatsdClient"/> class. /// </summary> /// <param name="channel">Channel to send metrics to</param> /// <param name="prefix">Prefix which is will be for every metric.</param> /// <param name="initialQueueSize">Initial size of queue for background metrics</param> /// <param name="exceptionHandler">Action to perform on an unhandled exception. Most commoly it's used for logging</param> public BackgroundStatsdClient(IChannel channel, string prefix = null, int initialQueueSize = 0, Action <Exception> exceptionHandler = null) { if (channel == null) { throw new ArgumentNullException(nameof(channel)); } if (prefix != null && (string.IsNullOrWhiteSpace(prefix) || prefix.EndsWith("."))) { const string message = "Must be either null or period delimited string and not end with '.'." + " For instance, 'my.favorite.prefix' is a right one"; throw new ArgumentException(message, nameof(prefix)); } _queue = new MetricsQueue(initialQueueSize); _sender = new SendWorker(_queue, channel, prefix, exceptionHandler); }
private ChessEngineManager() { procEngine = null; queReceived = null; queSyncRoot = new object(); //swWRiter = null; threadSend = null; sendWorker = null; //srReader = null; //srErrReader = null; cmdParser = null; DefaultConfigData = null; CurrentConfigData = null; IsEngineInit = false; IsEngineRunning = false; IsPonderMode = false; IsPonderFailed = false; IsWaitforNewGame = false; IsForceStop = false; }
private void Send(HandlerMessage message) { message.Context.SendEventArgs.UserToken = message; message.Context.SendReady.Wait(); try { // mjb /* List<ArraySegment<byte>> data = message.IsRaw ? message.DataFrame.AsRaw() : message.DataFrame.AsFrame(); message.Context.SendEventArgs.BufferList = data; message.Context.Connection.Client.SendAsync(message.Context.SendEventArgs); */ if (message.Context.SslStream != null) { SendWorker sw = new SendWorker() { message = message }; Thread wt = new Thread(sw.Send); wt.Start(); } else { List<ArraySegment<byte>> data = message.IsRaw ? message.DataFrame.AsRaw() : message.DataFrame.AsFrame(); message.Context.SendEventArgs.BufferList = data; message.Context.Connection.Client.SendAsync(message.Context.SendEventArgs); } } catch { message.Context.Disconnect(); } }
// interface //public IEnumerator Start() { public void Start() { // clear received command respond que queReceived = new Queue<string>(); try { procEngine = new Process(); procEngine.StartInfo.FileName = strProcPath; //procEngine.StartInfo.WorkingDirectory = @"ChessEngine\"; //procEngine.StartInfo.Arguments = "uci"; procEngine.StartInfo.CreateNoWindow = true; procEngine.StartInfo.UseShellExecute = false; procEngine.StartInfo.ErrorDialog = false; procEngine.StartInfo.RedirectStandardOutput = true; procEngine.StartInfo.RedirectStandardInput = true; procEngine.StartInfo.RedirectStandardError = true; // Set our event handler to asynchronously read the sort output/err. procEngine.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler); procEngine.ErrorDataReceived += new DataReceivedEventHandler(StandardErrorHandler); // start chess engine(stockfish) procEngine.Start(); // Start the asynchronous read of the output stream. procEngine.BeginOutputReadLine(); procEngine.BeginErrorReadLine(); //swWRiter = procEngine.StandardInput; //swWRiter.AutoFlush = true; //srReader = procEngine.StandardOutput; //srErrReader = procEngine.StandardError; cmdParser = new ChessEngineCmdParser() { Cmd = null }; DefaultConfigData = new ChessEngineConfig(); CurrentConfigData = new ChessEngineConfig(); // wait for 2.0 sec for process thread running //yield return new WaitForSeconds(2.0f); //yield return new WaitForSeconds(5.0f); sendWorker = new SendWorker( procEngine.StandardInput ); threadSend = new Thread(sendWorker.ProcessSend); threadSend.Start(); IsEngineRunning = true; } catch( System.Exception e ) { UnityEngine.Debug.LogError( "ChessEngineManager - Start() Failed!!! because of" + e.Message ); } }
public void End() { if( IsEngineRunning ) { queReceived.Clear(); sendWorker.RequestStop(); threadSend.Join(); threadSend = null; sendWorker = null; // 비동기 로딩 스트림은 클로즈 하면 안된다!!! //srReader.Close(); //srErrReader.Close(); procEngine.CancelOutputRead(); procEngine.CancelErrorRead(); procEngine.Close(); procEngine = null; cmdParser = null; DefaultConfigData = null; CurrentConfigData = null; IsEngineRunning = false; IsEngineInit = false; } }
public static void SupperSend(IPEndPoint ip, string path, SendWorker worker, Action <string, int, bool, double> statusHandler = null, Action <string, long> speedHandler = null) { try { Stopwatch watcher = new Stopwatch(); watcher.Start(); FileInfo file = new FileInfo(path); #if DEBUG if (!file.Exists) { throw new FileNotFoundException(); } #endif long fileLength = file.Length; if (!worker.Client.Connected) { worker.Client.Connect(ip); } Buffer.BlockCopy(BitConverter.GetBytes(fileLength), 0, worker.Buffer, 0, PerLongCount); string fileName = file.Name; worker.Client.Send(worker.Buffer, 0, PerLongCount + Encoding.Default.GetBytes(fileName, 0, fileName.Length, worker.Buffer, PerLongCount), SocketFlags.None); Console.WriteLine("Sending file:" + fileName + ".Plz wait..."); int threadCount = GetThreadCount(fileLength); SendWorker[] workers = new SendWorker[threadCount]; for (int i = 0; i < threadCount; i++) { workers[i] = i == 0 ? worker : new SendWorker(ip); } int perPairCount = PerLongCount * 2, count = perPairCount * threadCount; byte[] bufferInfo = new byte[count]; long oddSize, avgSize = Math.DivRem(fileLength, (long)threadCount, out oddSize); if (worker.Client.Receive(bufferInfo) == 4) { for (int i = 0; i < threadCount; i++) { workers[i].Initialize(path, i * avgSize, i == threadCount - 1 ? avgSize + oddSize : avgSize); } } else { long w, t; for (int i = 0; i < threadCount; i++) { Read(out w, bufferInfo, i * perPairCount); Read(out t, bufferInfo, i * perPairCount + PerLongCount); workers[i].Initialize(path, i * avgSize, i == threadCount - 1 ? avgSize + oddSize : avgSize, w, t); } } AutoResetEvent reset = new AutoResetEvent(true); for (int i = 0; i < threadCount; i++) { workers[i].RunWork(i == threadCount - 1 ? reset : null); } reset.WaitOne(); string id = ip.ToString() + "|" + path; long speed; long diff; long value = 0L; int percent; double ms0 = watcher.ElapsedMilliseconds; do { Thread.Sleep(500); diff = workers.ReportSpeed(ref value, out percent); double ms1 = watcher.ElapsedMilliseconds; speed = (long)((diff * 1000) / (ms1 - ms0)); Console.WriteLine("waiting for other threads. Progress:" + value + "/" + fileLength + ";Speed:" + Common.ByteConvertToGBMBKB(speed) + "/S."); //int percent = (int)Math.Round(value * 100.0 / fileLength); if (speedHandler != null) { speedHandler.Invoke(id, speed); } if (statusHandler != null) { statusHandler.Invoke(id, percent, false, ms1); } ms0 = watcher.ElapsedMilliseconds; }while (!workers.IsAllFinished()); watcher.Stop(); Console.WriteLine("Send finish.Span Time:" + watcher.Elapsed.TotalMilliseconds + " ms."); if (speedHandler != null) { speedHandler.Invoke(id, speed); } if (statusHandler != null) { statusHandler.Invoke(id, 100, true, watcher.Elapsed.TotalMilliseconds); } } catch (Exception e) { Console.WriteLine("发送出错:" + e.Message); } }