Disposes of the resources (other than memory) used by the .
/// <summary> /// 清除定时器 /// </summary> public void ClearTimer() { try { _timer.Elapsed -= Checklive; _timer.Stop(); _timer.Close(); _timer.Dispose(); } catch { Thread.Sleep(1000 * 3);//休息3秒再清除定时器 try { _timer.Elapsed -= Checklive; _timer.Stop(); _timer.Close(); _timer.Dispose(); } catch (Exception ex) { LogManager.DefaultLogger.DebugFormat("ClearTimer Error:{0}", new { _imuserid, _channelid, _sourcetype, err = ex.ToString() }.ToJson()); } } }
private void timer_Elapsed(object sender, ElapsedEventArgs e) { try { if (!this.IsDisposed && timer.Enabled) { this.Invoke(new Action(delegate() { lblTime.Text = DateTime.Now.ToString(); } )); } } catch (Exception ex) { // 시간관련하여 컨트롤에 에러가 발생한 경우 //CustomMessageBox.ShowDialog("에러", ex.Message, MessageBoxIcon.Error); if (timer.Enabled) { timer.Stop(); timer.Enabled = false; timer.Close(); } WriteLog(ex); } }
/// Hanldes the bridge of data streams from Millennium interface to Opera server through this middleware, simply takes incoming and sends outgoing data private static void ExchangePackets(NetworkStream FirstStream, NetworkStream SecondStream) { SetTimer(SecondStream); Console.WriteLine(Thread.CurrentThread.Name + " has started..."); while (Status == 0) { try { //Console.WriteLine("Still a connection"); if (FirstStream.CanRead) { // create datastream format byte[] myReadBuffer = new byte[1024]; //byte[] myReadBuffer2 = new byte[1024]; StringBuilder myCompleteMessage = new StringBuilder(); MemoryStream ms = new MemoryStream(); int numberOfBytesRead = 0; //int numberOfBytesRead2 = 0; int TotalBytesRead = 0; // Incoming message may be larger than the buffer size. while (FirstStream.DataAvailable & Status == 0) { numberOfBytesRead = FirstStream.Read(myReadBuffer, 0, myReadBuffer.Length); ms.Write(myReadBuffer, TotalBytesRead, numberOfBytesRead); myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)); TotalBytesRead = TotalBytesRead + numberOfBytesRead; Thread.Sleep(500); } // write data to console and then send on to other leg of stream if (SecondStream.CanWrite & Status == 0 & numberOfBytesRead > 0) { InUse = true; Console.WriteLine("You received the following message from " + Thread.CurrentThread.Name + " :" + myCompleteMessage); byte[] myWriteBuffer = ms.ToArray(); SecondStream.Write(myWriteBuffer, 0, myWriteBuffer.Length); InUse = false; } } else { Status = 1; aTimer.Stop(); aTimer.Close(); break; } } catch (Exception ex) { Console.WriteLine(Thread.CurrentThread.Name + " error: " + ex.Message); aTimer.Stop(); aTimer.Close(); } } Console.WriteLine(Thread.CurrentThread + " closed"); Status = 1; aTimer.Stop(); aTimer.Close(); }
public void StopRdrPolling() { pollReaderTimer.Enabled = false; pollReaderTimer.Close(); pollReaderTimer.Dispose(); trunOnRdrPolling = false; }
private void startOrStopApp() { if (applist.Count != 0) { //Start if (Settings.Default.AppEnabled == false) { foreach (AppMember item in applist) { if (Convert.ToDouble(item.Time) < 2.00) { MessageBox.Show("部分游戏时间不足2小时,可能不会出卡", "注意"); break; } } Kill(); startToolStripMenuItem.Text = "停止"; Start(); } else { appTimer.Stop(); appTimer.Close(); Kill(); startToolStripMenuItem.Text = "开始"; CMDprint("用户手动停止挂机"); try { LoadAppMsg((int)Status.Exit, applist[AppIndex].Id); } catch { } } } }
/// <summary> /// Initialize the USB Clover Transport and start watching USB events /// </summary> private void init() { //start listening for connection events listenForUSB(); initializeBGWDoWorkHandlers(); ConnectDevice(); // Create a timer that will check the connection to // ensure that it is still up and healthy. There // are circumstances where Windows might put the // USB port to sleep and not wake it up, so this code // proactively checks the connection and re-establishes // it if necessary. if (getPingSleepSeconds() > 0) { if (_timer != null) { _timer.Close(); Console.WriteLine("Timer thread closed"); } else { _timer = new System.Timers.Timer(); } _timer.AutoReset = false; _timer.Interval = getPingSleepSeconds() * 1000; _timer.Elapsed += new ElapsedEventHandler(OnTimerEvent); Console.WriteLine("Timer Thread created"); _timer.Start(); } }
public override void TearDown() { if (statusPoller != null) { statusPoller.Close(); statusPoller.Dispose(); statusPoller = null; } }
/// <summary> /// 画面を閉じてタイマーのリソースを開放する /// </summary> private void StopTimer() { this.Invoke((MethodInvoker) delegate { this.Hide(); }); timer.Stop(); timer.Close(); }
public void StopTimer() { if (IsRunning) { IsRunning = false; if (timer != null) { timer.Close(); } } }
/// <summary> /// 检查断线状态 /// </summary> private void CheckState(object source, ElapsedEventArgs elapsedEventArgs, object sourceArgs) { missCount++; if (missCount > 60) { Stop(); timerCheckStatic.Close(); timerCheckStatic = null; } else if (missCount > 7) { State = RecviceState.Waiting; } }
public static int scheduleEvent(Event newEvent, uint intervalMinutes, bool snapToHour=false, ushort minimumPlayers=0, uint durationSeconds=0, uint[] countDownTimes=null) { ScheduledEvent scheduledEvent = (durationSeconds == 0 ? new ScheduledEvent(newEvent, intervalMinutes, minimumPlayers, countDownTimes) : new ScheduledEvent(newEvent, intervalMinutes, minimumPlayers, countDownTimes, durationSeconds)); if(snapToHour) { int minuteToStart = (int)(intervalMinutes * (DateTime.Now.Minute/intervalMinutes) + intervalMinutes); int timeToWait = (minuteToStart * 60000) - (DateTime.Now.Minute*60000 + DateTime.Now.Second*1000 + DateTime.Now.Millisecond); Timer waitTimer = new Timer(timeToWait); waitTimer.AutoReset = false; waitTimer.Elapsed += delegate { scheduledEvent.beginRecurrence(); waitTimer.Close(); }; waitTimer.Start(); } else scheduledEvent.beginRecurrence(); scheduledEvents.Add(scheduledEvent); return scheduledEvents.IndexOf(scheduledEvent); }
private void Start_Again() { ball_real_cord_y = 0; // lets try this RandomXLocation location = new RandomXLocation(); //new thread ball_real_cord_x = location.get_ball_x_start_coord(); ball_int_y_cord = (int)(ball_real_cord_y); ////////// this back to 0 ball_int_x_cord = (int)(ball_real_cord_x); ball_refresh_clock.Enabled = false; // ball direction logic Logic algorithm = new Logic(); ball_radians = algorithm.get_direction_for_ball(); ball_horizontal_delta = distance_move_per_refresh * Math.Cos(ball_radians); ball_vertical_delta = distance_move_per_refresh * Math.Sin(ball_radians); // end of lets try this distance_move_per_refresh += .25; ball_clock_active = false; graphical_area_refresh_clock.Close(); ball_refresh_clock.Close(); //CreateGraphics().Clear(ActiveForm.BackColor); UpdateFrom(); ball_clock_active = true; ball_refresh_clock.Enabled = true; graphical_area_refresh_clock.Enabled = true; Start_a_clock(ball_update_rate); Start_graphic_clock(graphicalarearefresh); }
private void OnStartButtonToggled(bool pressed) { if (pressed) { startBt.Text = "Stop"; currTimer = new System.Timers.Timer() { AutoReset = false, Interval = 60000, Enabled = true }; currTimer.Elapsed += (z, zz) => { currTimer.Close(); currTimer.Dispose(); currTimer = null; startBt.Text = "Start"; startBt.Pressed = false; }; clicksLb.Text = 0.ToString(); futureTime = DateTime.Now.AddMilliseconds(currTimer.Interval); } else { startBt.Text = "Start"; if (currTimer != null) { currTimer.Stop(); currTimer.Close(); currTimer.Dispose(); } currTimer = null; } }
private void OnTimedEvent(object source, ElapsedEventArgs e) { isActive = false; keepAliveTimer.Stop(); keepAliveTimer.Close(); cc.OnNodeFailure(areaName); }
public static void TimerStop() { CoreCount = 0; IsRunning = false; Core.Stop(); Core.Close(); }
public void FreeResources() { log.Info("FreeResources"); Stop(); if (fileWatchers != null) { foreach (FileSystemWatcher watcher in fileWatchers) { if (watcher != null) { watcher.Changed -= new FileSystemEventHandler(OnChanged); watcher.Dispose(); } } } if (timer != null) { timer.Stop(); timer.Close(); } fileWatchers = null; timer = null; }
internal void Close() { if (_ssl != null) { _ssl.Close(); } _ssl = null; if (_tcpTimer != null) { _tcpTimer.Close(); } _tcpTimer = null; if (_processThread != null) { _processThread.Abort(); } _processThread = null; if (_reader != null) { _reader.Close(); } _reader = null; if (_writer != null) { _writer.Close(); } _writer = null; if (_tcpClient != null) { _tcpClient.Close(); } }
public void FreeResources() { if (isWatching) { EnableWatchers(false); } if (!ReferenceEquals(fileWatchers, null)) { foreach (FileSystemWatcher watcher in fileWatchers) { if (ReferenceEquals(watcher, null)) { continue; } watcher.Changed -= new FileSystemEventHandler(OnChanged); watcher.Dispose(); } } if (!ReferenceEquals(timer, null)) { timer.Stop(); timer.Close(); } fileWatchers = null; timer = null; }
/// <summary> /// Stop program button. /// </summary> /// <param name="sender">Object source.</param> /// <param name="e">Routed event args.</param> private void StopButton_Click(object sender, RoutedEventArgs e) { blink.Stop(); blink.Close(); blink.Dispose(); this.WindowState = WindowState.Minimized; }
private void OnStopping() { this.logger.LogInformation("OnStopping method called."); int seconds = 0; while (!processCompleted) { Thread.Sleep(1000); seconds++; if (stopServiceTimeout > 0 && (seconds * 1000) > stopServiceTimeout) { break; } } try { _timer?.Stop(); _timer?.Close(); _timer?.Dispose(); } catch (Exception ex) { this.logger.LogError(ex, ex.Message); } }
public static void HalfSecondTimerStop() { HalfSecondIsRunning = false; HalfSecond.Stop(); HalfSecond.Close(); HalfSecond.Dispose(); }
internal void StopServer() { // TODO : 아직 서버 실행 시 Attach 가 정상적으로 되지 않음... // overlayAPI.DetachACTEvent(); if (httpServer != null) { httpServer.Stop(); foreach (var s in httpServer.WebSocketServices.Hosts) { httpServer.RemoveWebSocketService(s.Path); } httpServer = null; } if (updateTimer != null) { updateTimer.Stop(); updateTimer.Close(); updateTimer = null; } if (pingTimer != null) { pingTimer.Stop(); pingTimer.Close(); pingTimer = null; } }
public void LockCloseWindow(uint childMarker) { try { if (UIThreadCheck()) { return; } // all done close program // Note, any mmOpen call can take 20+ seconds if the URL does not exist, // this is when the UI thread will also be writing error ststus to the screen // _thread.Join() in _interface.Stop(); will deadlock (see InvokeRequired calls in MMWindow) // if we use the UI thread for the sync functionality (ie we want to clean up properly) // we use a new task thread which we should be on _closing = true; // used in _watchDog _interface.Stop(); // stop and cleanup nicely while (_watchDog.Enabled != false) { System.Threading.Thread.Sleep(100); } _watchDog.Close(); // safe to close correctly // call this function with lParam set MMInterop.SendMessage(GetHWND(), MMInterop.WM_CLOSE, IntPtr.Zero, (IntPtr)1); } catch { Debug.Assert(false); } return; }
public virtual void RemoveRegion(IScene scene) { if (!m_Enabled) { return; } lock (m_scene) { m_Enabled = false; RemoveHandlers(); m_scene = null; } if (UpdateMapImage != null) { UpdateMapImage.Stop(); UpdateMapImage.Elapsed -= OnTimedCreateNewMapImage; UpdateMapImage.Enabled = false; UpdateMapImage.Close(); } if (UpdateOnlineStatus != null) { UpdateOnlineStatus.Stop(); UpdateOnlineStatus.Elapsed -= OnUpdateRegion; UpdateOnlineStatus.Enabled = false; UpdateOnlineStatus.Close(); } }
public static void ReleaseServer() { if (server != null) { if (client != null && client.Connected)//wait until receive timeout to let client disconnect { Thread.Sleep(11000); } if (ClientCheckingTimer != null)//stop check timer { ClientCheckingTimer.Stop(); ClientCheckingTimer.Close(); } if (receiveThread != null)//stop all thread { reciveblock = false; receiveThread.Abort(); client = null; threadblock = false; } try { server.Close();//close server, this will trigger server.accept() exception and it is the only way to close server right now } catch (Exception e) { Console.WriteLine("commer server close error" + e.Message); } } }
/// <summary> /// 关闭socket /// </summary> public void Close() { if (timerSend != null) { timerSend.Close(); } if (threadConnect != null) { threadConnect.Abort(); } if (threadHeartBreak != null) { threadHeartBreak.Abort(); } if (socketClient != null) { socketClient.Close(); socketClient = null; } queueLog.Enqueue("关闭读线程1"); if (threadRead != null) { threadRead.Abort(); } queueLog.Enqueue("客户端关闭"); conneted = false; }
private void OnTimedEventremoveplayer(Object source, ElapsedEventArgs e) { if (lifetime-- <= 0) { if (islocalplayer) { room.Remove(this); mchannelmanager.mudpclient.mudpserver.removeclient(mchannelmanager.mudpclient.mremoteEP);//remove thisUdpChannelManager } else { localplayer.proxyclients_list.Remove(this); } mchannelmanager.DestoryChannel(mchannelid); aTimer.Close(); Console.WriteLine("mchannelmanager.DestoryChannel" + mchannelid); } FDataPackage mp = new FDataPackage(""); mp.MT = DataType.PING; String str = JsonConvert.SerializeObject(mp); sendreliable(ref str); }
public void Dispose() { StopGenerate(); _timer.Elapsed -= OnTimerTick; _timer.Close(); _timer.Dispose(); }
public void Close() { try { _server?.Close(); _server = null; } catch (Exception) { // ignored } try { _currentThread?.Abort(); } catch (Exception e) { Log(API.LogType.Error, "Error while interrupting thread: {0}\n{1}", e.Message, e.StackTrace); } _currentThread = null; _timer.Close(); Log(API.LogType.Debug, "Stopped."); }
public static Timer DelayedCall(double delay, TimerCallback callback) { Timer newTimer = null; Timer returnTimer = null; try { newTimer = new Timer(Math.Max(delay, 1)); newTimer.AutoReset = false; newTimer.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs args) { try { callback(); } catch (Exception ex) { Logger.Fatal(Strings.UnhandledExceptionCaught, ex.ToString()); Environment.FailFast(Strings.UnhandledExceptionCaught2 + "\r\n" + ex.ToString()); } }); newTimer.Enabled = true; returnTimer = newTimer; newTimer = null; } finally { if (newTimer != null) { newTimer.Close(); } } return returnTimer; }
/// <summary> /// 机器人移动目标改变 /// </summary> public void ChangeRobortMoveState(object source, ElapsedEventArgs e) { foreach (Player p in cdicMembers.Values) { RobortMoveInfo stMove; stMove.nPlayerID = p.NPlayerID; Random r = new Random(Guid.NewGuid().GetHashCode()); stMove.nX = r.Next(100, SubStepData.width); stMove.nY = r.Next(100, SubStepData.height); byte[] btMove = Common.Method.StructToBytes(stMove); if (null == p.m_pCurStep) { if (null != RobortTimer) { RobortTimer.Close(); } return; } Team.TeamMAD(((BattleStep)p.m_pCurStep).PTeamA, (byte)ProtorlEnum.FrameGroup.FrameGroup_ServerToUser, (byte)ProtorlEnum.FrameType_ServerToUser.FrameType_RobortMove, btMove); Team.TeamMAD(((BattleStep)p.m_pCurStep).PTeamB, (byte)ProtorlEnum.FrameGroup.FrameGroup_ServerToUser, (byte)ProtorlEnum.FrameType_ServerToUser.FrameType_RobortMove, btMove); } }
public static void CoreTimerStop() { CoreIsRunning = false; Core.Stop(); Core.Close(); Core.Dispose(); }
/// <summary> /// Creates a new <c>DrawQuery</c> that refers to the specified feature type(s), /// drawing the results of the spatial query to the specified display. /// </summary> /// <param name="index">The index to query</param> /// <param name="display">The display to draw to</param> /// <param name="style">The drawing style</param> /// <param name="types">The type(s) of spatial feature to draw</param> public DrawQuery(ISpatialIndex index, ISpatialDisplay display, IDrawStyle style, SpatialType types) { m_Display = display; m_Style = style; m_DoPaint = false; Timer t = new Timer(500); t.Elapsed += new ElapsedEventHandler(Timer_Elapsed); t.Start(); index.QueryWindow(m_Display.Extent, types, OnQueryHit); t.Close(); display.PaintNow(); }
static void Main(string[] args) { try { // Add to the console Console.Title = "Sius"; Console.WriteLine("Sius"); Console.Write("Press any key to exit ..." + Environment.NewLine); Time = DateTime.Now; // Check if we are logging if (!string.IsNullOrEmpty(SiusConf.GetSetting.String("logging"))) SiusLog.Logging = true; // Check if we want to clear the log before starting if (SiusConf.GetSetting.Boolean("clearlog")) SiusLog.ClearLogFile(); // Create the SQLite database and tables SQLite.Connect(); // Log that Sius has successfully started SiusLog.Log(SiusLog.INFORMATION, "server","Sius successfully started."); // Initialize the Transmission Control Protocol (TCP) connection Listen tcp = new Listen(); tcp.StartListening(); // Start the Ping timer System.Timers.Timer SendPing = new System.Timers.Timer(); SendPing.Elapsed += new ElapsedEventHandler(Protocol.Ping.OnTimedEvent); if (SiusConf.GetSetting.Integer("ping") >= 10) SendPing.Interval = SiusConf.GetSetting.Integer("ping") * 1000; else SendPing.Interval = 150000; // 150 seconds SendPing.Enabled = true; SendPing.Start(); // Start the Scorereset timer System.Timers.Timer Scorereset = new System.Timers.Timer(); Scorereset.Elapsed += new ElapsedEventHandler(Protocol.Scorereset.OnTimedEvent); if (SiusConf.GetSetting.Integer("scorereset") >= 1) Scorereset.Interval = SiusConf.GetSetting.Integer("scorereset") * 3600000; else Scorereset.Interval = 1209600000; // 2 weeks Scorereset.Enabled = true; Scorereset.Start(); // Wait until we're told to exit the program while (Running == true) { // press any key to exit Console.ReadKey(true); Running = false; SendPing.Close(); Scorereset.Close(); } // Cleanup and end all TCP connections Sius.Connected = false; SiusLog.Log(SiusLog.INFORMATION, "server","Exiting"); tcp.RequestStop(); // Append a line to the log to mark the end of a run. SiusLog.DirectLogToFile("-----------------------------------------------------"); } catch (Exception e) { // Log any unexpected errors SiusLog.Log(SiusLog.ERROR, "server", "Error: " + e.StackTrace); } }
public void FindLyrics() { try { // timer _searchTimer = new Timer { Enabled = false, Interval = TimeLimit }; _searchTimer.Elapsed += TimerElapsed; _searchTimer.Start(); // Find Lyrics FindLyricsWithTimer(); } finally { if (_searchTimer != null) { _searchTimer.Stop(); _searchTimer.Close(); } } }
/// <summary> /// write data source to db /// </summary> private void WriteToDatabase() { //初始化超时标记 bool timeIsOver = false; //实始化消耗时间 TakeMilliseconds = 0x0; //创建超时定时器 Timer timer = new Timer(this._timeOut); timer.Elapsed += new ElapsedEventHandler((object source, ElapsedEventArgs e) => timeIsOver = true); timer.AutoReset = false; timer.Enabled = true; //创建秒表 Stopwatch stopwatch = new Stopwatch(); //检查列映射配置 VerifyColumnMapping(); //加载数据源列索引 LoadSourceColumnIndex(); //获取目标表结构信息 GetTableSchemaData(); //跳过指定行数 SkipRows(); OracleConnection oracleConnection; if (string.IsNullOrEmpty(this._connectionString)) { oracleConnection = this._oracleConnection; } else { oracleConnection = new OracleConnection(this._connectionString); } OracleCommand commandOracle = new OracleCommand(BuildBulkInsertCommandText(), oracleConnection) { BindByName = true }; commandOracle.Parameters.AddRange(BuildCommandParameter()); //需要绑定值的参数 IList<OracleParameter> parameterCollection = new List<OracleParameter>(); foreach (OracleParameter parameter in commandOracle.Parameters) { if (!this._dicNoInitValueParameters.ContainsKey(parameter.ParameterName)) { parameterCollection.Add(parameter); } } int intBatchIndex = 0x0; int intLineNo = 0x0; CopiedRowCount = 0x0; try { //开始记时 stopwatch.Start(); oracleConnection.Open(); while (ReadSource()) { if (timeIsOver) { throw new OracleBulkInsertException(BulkInsertCode.ExecuteTimeOut, (this._timeOut / OracleBulkInsert.ONE_SECONDS).ToString()); } //绑定参数值 SetParameterValue(intBatchIndex, parameterCollection); //设定行号 if (this._insertRowNumber) { ((object[])commandOracle.Parameters[_rowNumberColumn].Value)[intBatchIndex] = this._startRow - 1 + ++intLineNo; } //批次累加 ++intBatchIndex; //未达到提交批次 if (intBatchIndex % this._batchSize != 0) continue; commandOracle.ArrayBindCount = intBatchIndex; commandOracle.ExecuteNonQuery(); //设置提交行数 CopiedRowCount += intBatchIndex; //恢复批次 intBatchIndex = 0x0; } if (intBatchIndex % this._batchSize != 0) {//提交最后不足一批的剩余记录 commandOracle.ArrayBindCount = intBatchIndex; commandOracle.ExecuteNonQuery(); //设置提交行数 CopiedRowCount += intBatchIndex; } } catch (OracleBulkInsertException ex) { throw new OracleBulkInsertException(ex.Message, CopiedRowCount); } catch (Exception ex) { throw new OracleBulkInsertException(ex.ToString(), CopiedRowCount); } finally { //关闭定时器 timer.Enabled = false; timer.Close(); timer.Dispose(); //释放连接 oracleConnection.Close(); oracleConnection.Dispose(); //关闭数据源 CloseDatasource(); //关闭秒表 stopwatch.Stop(); TakeMilliseconds = stopwatch.ElapsedMilliseconds; } }
internal static void Launch() { Application.CurrentCulture = CultureInfo.InvariantCulture; Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); splash = new SplashForm(); splash.Show(); Timer timer = new Timer(); //Configure this timer to restart each second ( 1000 millis) timer.Interval = 1000; timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Start(); //splash.Refresh(); //Application.DoEvents(); Application.DoEvents(); MainModule.Initialize("data"); splash.SetLoadProgress(50); splash.Refresh(); Application.DoEvents(); UpdaterHelper.UpdateInfo info; info = UpdaterHelper.CheckFromUpdates(); Application.DoEvents(); if (info.UpdateAvailable) { UpdateForm updateForm; updateForm = new UpdateForm(info); updateForm.ShowDialog(); Application.DoEvents(); } splash.SetLoadProgress(60); splash.Refresh(); Application.DoEvents(); IconsManager.Initialize(); Application.DoEvents(); MainForm main = new MainForm(); //if (runSingleInstance) //{ // main.HandleCreated += new EventHandler(main_HandleCreated); //} GC.Collect(); timer.Stop(); timer.Close(); splash.SetLoadProgress(100); splash.Refresh(); Application.DoEvents(); splash.Close(); splash = null; Application.DoEvents(); Application.Run(main); }
/// <summary> /// Send a Tcp connection request to a new peer. /// </summary> /// <param name="Message">The request message.</param> /// <param name="PeerIP">The IP address of the new peer [IP:Port].</param> public static void SendConnectionRequest(string Message, string PeerIP) { Thread t = new Thread(new ParameterizedThreadStart( delegate { // converts UTF16 to Byte[] byte[] MessageByte = ASCIIEncoding.Unicode.GetBytes(Message); TcpClient client = new TcpClient(); NetworkStream stream = null; try { string[] subPeerIP = PeerIP.Split(':'); string ip = subPeerIP[0]; int port = int.Parse(subPeerIP[1]); // control the peer ip ControlPeerIPAddress(ref ip, port); // connect to peer client = new TcpClient(); client.Connect(ip, port); // get stream stream = client.GetStream(); // send the request stream.Write(MessageByte, 0, MessageByte.Length); Global.CountUploadRate += MessageByte.Length; // wait a reply System.Timers.Timer timer = new System.Timers.Timer(15000); timer.Elapsed += new ElapsedEventHandler(delegate { Thread.CurrentThread.Abort(); }); timer.Enabled = true; byte[] reply_message_byte = new byte[3072]; byte[] bytes = new byte[3072]; stream.Read(reply_message_byte, 0, reply_message_byte.Length); int i = 0; int num_bytes_read = 0; do { if (stream.DataAvailable) { stream.Read(bytes, 0, bytes.Length); Array.Copy(bytes, 0, reply_message_byte, num_bytes_read, i); num_bytes_read += i; } else { Thread.Sleep(10); if (!stream.DataAvailable) { break; } i = 1; } } while (i != 0); timer.Stop(); string reply = ASCIIEncoding.Unicode.GetString(reply_message_byte); string[] sub_reply = reply.Split('\n'); // if the peer have accepted the connection request if (sub_reply[0].Substring(0, 4) == "Nova" && sub_reply[1].Substring(0, 10) == "CONNECT_OK") { Utilities.Log.Write("Connection established with " + PeerIP, Utilities.Log.LogCategory.ConnectionRequests); // create a new peer object Objects.Peer peer = new Objects.Peer(PeerIP, client, stream); peer.ID = "EMPTY"; // send a EI-message string eiMessParam1; string eiMessParam2; if (Global.MessageEncryptionEnabled == true) { eiMessParam1 = "y"; eiMessParam2 = string.Format("{0},{1}", Utilities.Converterer.ConvertByteToHex(peer.MyAsymmetricEncryptionKey.N), Utilities.Converterer.ConvertByteToHex(peer.MyAsymmetricEncryptionKey.E)); } else { eiMessParam1 = "n"; eiMessParam2 = string.Empty; } // create and send a EI-message Messages.IMessage eiMess = Messages.MessagesFactory.Instance.CreateMessage(Messages.Commands.EI, false, eiMessParam1, eiMessParam2); peer.Send(eiMess); // add the peer in the list of the peers Lists.PeersList.AddPeer(peer); } else { stream.Close(); client.Close(); } timer.Close(); } catch { if (client != null) { client.Close(); } if (stream != null) { stream.Close(); } Utilities.Log.Write("The connection request hasn't been sent, probably the peer (" + PeerIP + ") is offline or disconnected", Utilities.Log.LogCategory.Error); } })); t.Name = "MessageSender_Connection_Request_Sending"; t.IsBackground = true; t.Start(); }
/// <summary> Runs the given test. </summary> /// <param name="endpoint">Chassis Manager Endpoint. </param> /// <param name="sequenceName">Sequence Name.</param> /// <param name="sequenceInstance">Sequence execution Instance.</param> /// <param name="parameters">Number of times to call the API.</param> /// <returns>a TestRun object with test results.</returns> public ResultOfTest Run( string endpoint, string sequenceName, int sequenceInstance, IDictionary<string, string> parameters, TimeSpan? apiSlaFromSequence, string userName, string userPassword) { Stopwatch stopwatch = null; ResultOfTest testRun = null; Timer timeoutTimer = null; if (!this.ApiSla.HasValue) { this.ApiSla = apiSlaFromSequence.HasValue ? apiSlaFromSequence : TimeSpan.FromSeconds(ApiSlaDefaultInSeconds); } HttpWebResponse response = null; try { var restParams = Helper.GetChassisManagerApiParameterList(this.Name).Select( rp => string.Format("{0}={1}", rp, parameters[rp])); testRun = new ResultOfTest() { Name = this.Name, IterationsExecutedSuccessfully = 0, RestUri = string.Format( "{0}/{1}{2}{3}", endpoint, this.Name, restParams.Any() ? "?" : string.Empty, string.Join("&", restParams)), StartTime = DateTime.UtcNow, State = TestRunState.Running, SequenceName = sequenceName, SequenceInstance = sequenceInstance }; ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }; Thread.Sleep((int)this.DelayBeforeStartInMS); stopwatch = Stopwatch.StartNew(); while (testRun.IterationsExecutedSuccessfully < this.Iterations && testRun.State != TestRunState.RunFailed) { // Sleep between iterations but not on first iteration. if (testRun.IterationsExecutedSuccessfully != 0) { Thread.Sleep((int)this.DelayBetweenIterationsInMS); } response = null; var httpWebRequest = (HttpWebRequest)WebRequest.Create(testRun.RestUri); httpWebRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); httpWebRequest.Credentials = CredentialCache.DefaultCredentials; httpWebRequest.UserAgent = Dns.GetHostName(); httpWebRequest.Method = "Get"; //if (runAsUserCredential == null) //{ // httpWebRequest.UseDefaultCredentials = true; // testRun.RunAsUserName = WindowsIdentity.GetCurrent().Name.Split('\\').LastOrDefault(); //} //else //{ // testRun.RunAsUserName = runAsUserCredential.UserName; // httpWebRequest.PreAuthenticate = true; // httpWebRequest.UseDefaultCredentials = false; // httpWebRequest.Credentials = new NetworkCredential(@"CMPVT02\dciBuild", "CSIBuild!"); //} testRun.RunAsUserName = userName; httpWebRequest.PreAuthenticate = true; httpWebRequest.UseDefaultCredentials = false; httpWebRequest.Credentials = new NetworkCredential(userName, userPassword); timeoutTimer = new Timer(this.ApiSla.Value.TotalMilliseconds); timeoutTimer.Elapsed += delegate(object sender, ElapsedEventArgs args) { Console.WriteLine( "\n!!!Timeout: Request {0} (Iteration:{1}) has not returned in SLA:{2} seconds; Total Lapsed time:{3} seconds\n", httpWebRequest.RequestUri, testRun.IterationsExecutedSuccessfully, this.ApiSla.Value.TotalSeconds, stopwatch.Elapsed.TotalSeconds); }; timeoutTimer.Start(); // Default is 100,000 = 100 seconds. changing it to 3,600,000 = 1 Hour. // TODO: Make this a parameter value instead of hard coded. httpWebRequest.Timeout = 3600000; stopwatch.Start(); response = (HttpWebResponse)httpWebRequest.GetResponse(); stopwatch.Stop(); testRun.ProcessResponse(response); } } catch (System.Net.WebException ex) { if (stopwatch.IsRunning) { stopwatch.Stop(); } if (ex.Response != null) { testRun.ProcessResponse((HttpWebResponse)ex.Response); } else { testRun.State = TestRunState.RunFailed; testRun.ErrorMessage = ex.ToString(); } } catch (Exception ex) { if (stopwatch.IsRunning) { stopwatch.Stop(); } testRun.State = TestRunState.RunFailed; testRun.ErrorMessage = ex.ToString(); } finally { if (timeoutTimer != null) { timeoutTimer.Close(); timeoutTimer.Dispose(); } testRun.TotalExecutionTime = stopwatch.Elapsed; testRun.AverageExecutionTime = testRun.IterationsExecutedSuccessfully == 0 ? TimeSpan.Zero : TimeSpan.FromTicks( testRun.TotalExecutionTime.Ticks / testRun.IterationsExecutedSuccessfully); } return testRun; }
private void StreamerRoutine() { // Sets timer for big frame streaming System.Timers.Timer lBigFrameTimer = new System.Timers.Timer(); // On timer elapsed executes OnBigFrameEvent lBigFrameTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnBigFrameEvent); // Timer elapses every MS_VIDEO_BIGFRAME ms lBigFrameTimer.Interval = Constants.MS_VIDEO_BIGFRAME; // Timer restarts when elapsed lBigFrameTimer.AutoReset = true; // Enables timer lBigFrameTimer.Enabled = true; // Sets timer for cursor position frame System.Timers.Timer lCursorTimer = new System.Timers.Timer(); // On timer elapsed executes OnCursorPositionEvent lCursorTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnCursorPositionEvent); // Timer elapses every MS_CURSOR_POSITION lCursorTimer.Interval = Constants.MS_CURSOR_POSITION; // Timer restarts when elapsed lCursorTimer.AutoReset = true; // Enables timer FIXME lCursorTimer.Enabled = true; // Creates and initialise streaming semaphore: used to make start every // group of diff frame calculation only when previous group has finished this._state.StreamingSem = new Semaphore(0, Constants.NUM_ROWS_GRID * Constants.NUM_ROWS_GRID); // While server is online while (this._state.WorkEnd == false) { // If video streaming is on if (this._state.VideoOn == true) { if (this._state.hWnd == IntPtr.Zero) { // Gets an array of Int32 that symbolizes current snapshot of area to stream if (this._state.CurrentBMP == null) this._state.CurrentBMP = this.GetBitmapInt32ArrayFromScreen(); this._state.PreviousBMP = this._state.CurrentBMP; // Gets another array of Int32 that symbolizes current snapshot of area to stream this._state.CurrentBMP = this.GetBitmapInt32ArrayFromScreen(); } else { if (this._state.CurrentBMP == null) this._state.CurrentBMP = this.GetBitmapInt32ArrayFromWindow(this._state.hWnd); this._state.PreviousBMP = this._state.CurrentBMP; this._state.CurrentBMP = this.GetBitmapInt32ArrayFromWindow(this._state.hWnd); } // Gets width and height of sub areas to give to ThreadPool worker threads Int32 lWidth = this._state.Area.Width / Constants.NUM_ROWS_GRID; Int32 lHeight = this._state.Area.Height / Constants.NUM_ROWS_GRID; Int32 lWRem = this._state.Area.Width % Constants.NUM_ROWS_GRID; Int32 lHRem = this._state.Area.Height % Constants.NUM_ROWS_GRID; //TODO : optimize this //Sends work items to ThreadPool worker threads for (Int32 lX = 0; lX + lWidth + lWRem <= this._state.Area.Width; lX += lWidth) for (Int32 lY = 0; lY + lHeight + lHRem <= this._state.Area.Height; lY += lHeight) ThreadPool.QueueUserWorkItem(CreateDiffFrame, (Object)new Rectangle(this._state.Area.X + lX, this._state.Area.Y + lY, lWidth + lWRem, lHeight + lHRem)); // Waits that previous group of diff frame calculations has finished for (int i = 0; i < Constants.NUM_ROWS_GRID * Constants.NUM_ROWS_GRID; i++) this._state.StreamingSem.WaitOne(); Thread.Sleep(Constants.MS_SLEEP_TIMEOUT_DIFFFRAME); } else Thread.Sleep(Constants.MS_SLEEP_TIMEOUT_BG_THREADS); } // Releases resources this._state.StreamingSem.Close(); this._state.StreamingSem.Dispose(); lBigFrameTimer.Stop(); lBigFrameTimer.Close(); lBigFrameTimer.Dispose(); lCursorTimer.Stop(); lCursorTimer.Close(); lCursorTimer.Dispose(); }
public void Start() { IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, PORT); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Timers.Timer timerAlive = new System.Timers.Timer(); timerAlive.Elapsed += new ElapsedEventHandler(OnTimerAlive); timerAlive.Interval = 1000; timerAlive.Enabled = true; try { socket.Bind(localEndPoint); socket.Listen(100); while (!_cancel) { _signal.Reset(); socket.BeginAccept(new AsyncCallback(ConnectCallback), socket); _signal.WaitOne(); } } catch (SocketException ex) { OnServerError(); if (socket.IsBound) socket.Shutdown(SocketShutdown.Both); string msg = "Network Error:\n" + ex.Message; MessageBox.Show(msg, Info.Title(), MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { timerAlive.Close(); socket.Close(); foreach (var client in clients.ToArray()) ClientRemove(client); } }
public void GetAlbumInfo() { try { _searchTimer = new Timer { Enabled = false, Interval = TimeLimit }; _searchTimer.Elapsed += TimerElapsed; _searchTimer.Start(); GetAlbumInfoWithTimer(); } finally { if (_searchTimer != null) { _searchTimer.Stop(); _searchTimer.Close(); } } }
void DelayedPlaySound(Sounds s, TimeSpan delay) { Timer t = new Timer(delay.TotalMilliseconds); t.Elapsed += (sender, e) => { PlaySound(s); t.Close(); }; t.Start(); }
public void removeTime(Timer t) { bool fail = false; //int index = 0; do { try { var copy = new List<TimerEvent>(); for(var i=_timers.Count - 1;i>=0;i--) { //index = i; if(i <= _timers.Count) { copy.Add(_timers[i]); } } var a = copy.FirstOrDefault(c => c != null && c.Timer == t); _timers.Remove(a); fail = false; } catch(Exception e) { //t.Close(); fail = true; //Console.WriteLine("[" + DateTime.Now + "] - Error removetime fail : " + t.GetHashCode() + " // Ex : " + e.Message + " // index : " + index + " // " + _timers.Count); //var a2 = _timers.Find(c => c != null && c.Timer == t); //_timers.Remove(a2); } } while (fail); t.Close(); }
/// <summary> /// Start the url relocation check /// </summary> public void CheckUrl() { //check if attempt<max_attempts //if not add urc to queue //and start a timer until there are no open urc's left // //if attempts slot left just connect /* if (QueueTimer != null) { QueueTimer.Stop(); QueueTimer.Dispose(); QueueTimer.Close(); } */ if (url == "") { Console.WriteLine("empty url to check ?"); return; } bool attempts_left = false; lock (AttemptsLock) { if (Attempts < MaxAttemptsNum) attempts_left = true; } if (attempts_left) { Attempts++; } else { lock (QueueLock) { Queue.Add(this); } if (QueueTimer == null) { Console.WriteLine("Attempts overflow: starting queue timer"); QueueTimer = new Timer(QueueUpdateInterval); QueueTimer.AutoReset = true; QueueTimer.Elapsed += delegate(object sender, ElapsedEventArgs e) {//an interesting question is if this block is locked ? ;-) //Console.WriteLine("queue timer interval elapsed\nAttempts running: " + Attempts + "\nItems in Queue: " + Queue.Count); lock (QueueLock) { if (Attempts < MaxAttemptsNum && Queue.Count > 0) { //now use up all free slots by activating new checks and increase the attempts num int end = MaxAttemptsNum - Attempts; if (end > Queue.Count) end = Queue.Count; //Console.WriteLine("checking " + end + " queue items."); for (int i = 0; i < end; i++) { //lock (AttemptsLock) //{ Attempts++; //} Queue[i].Connect(); } Queue.RemoveRange(0, end); } if (Queue.Count == 0) { Console.WriteLine("finished all urls in the relocation check queue.\nStopping Timer."); QueueTimer.Stop(); QueueTimer.Dispose(); QueueTimer.Close(); QueueTimer = null; //GC.Collect(); } } }; QueueTimer.Start(); } return; } Connect(); }
public DiagnosticWindow() { InitializeComponent(); this.Loaded += (s, e) => { App.diagnosticModelActor.Tell(DiagnosticsCollector.REQUESTHISTORY); }; gauges.ItemsSource = gaugeSource; messages.ItemsSource = messageSource; inProgress.ItemsSource = inProgressSource; errors.ItemsSource = errorSource; var thisProc = Process.GetCurrentProcess(); var timer = new Timer(refreshInterval); this.Closing += (sender, args) => { timer.Stop(); timer.Close(); timer.Dispose(); }; timer.Elapsed += (s, a) => { App.diagnosticWindow.Dispatcher.adopt(delegate { nics.ItemsSource = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().Where(nic => { return nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up; }).Select(nic => { return nic.GetIPv4Statistics(); }); procs.ItemsSource = Process.GetProcessesByName(thisProc.ProcessName).Union(Process.GetProcessesByName(App.proc.ProcessName)); }); }; timer.Start(); }
public int Start() { int rc = 0; string formatParms = ""; string formatFileName = ""; string path = ""; try { taskProcess = new Process(); taskProcess.StartInfo.UseShellExecute = false; //taskProcess.StartInfo.FileName = @"c:\XImportScriptIndexes.bat"; taskProcess.StartInfo.CreateNoWindow = true; // You can start any process, HelloWorld is a do-nothing example. // Execution Directory (from Dictionary). //path = string.Format("{0}", getDictionaryEntry("ExecutablePath", "")); string pathAndSlash = ""; if (taskPath.Length > 0) { pathAndSlash = taskPath + @"\"; } // Now use taskPath (member of XTRMTask)! if (taskExecutable.Length > 0) { //formatFileName = string.Format("{0}{1}", getDictionaryEntry("ExecutableLocation", ""), taskExecutable); //formatFileName = string.Format("{0}", taskExecutable); formatFileName = string.Format(@"{0}{1}", pathAndSlash, taskExecutable); } else { //formatFileName = string.Format("{0}{1}", getDictionaryEntry("ExecutableLocation", ""), taskName); //formatFileName = string.Format("{0}", taskName); formatFileName = string.Format(@"{0}{1}", pathAndSlash, taskName); } taskProcess.StartInfo.FileName = formatFileName; // Augment Path with TaskPath! // May want other environment variables... path = taskPath; if (path.Length > 0) { path += ";"; path += taskProcess.StartInfo.EnvironmentVariables["Path"]; taskProcess.StartInfo.EnvironmentVariables["Path"] = path; } // Impute (prepend) taskSerial as the first argument; followed by the remaining args in the order of their specification. int i = 0; //if (!formatFileName.Contains("XPerl")) //{ // formatParms = taskSerial.ToString(); //} foreach (string pX in taskParms) { if (i > 0) { if (pX != null) { if (pX.Length > 0) { formatParms += " "; formatParms += pX; //formatParms += ""; } } } i++; } taskProcess.StartInfo.Arguments = formatParms; // Hook up the Elapsed event for the timer. aTimer = new System.Timers.Timer(10000); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 2 seconds (2000 milliseconds). aTimer.Interval = 2000; aTimer.Enabled = true; taskProcess.EnableRaisingEvents = true; taskProcess.Exited += new EventHandler(taskProcess_Exited); taskOriginator = true; taskStatus = 1; taskStart = DateTime.Now.ToString(); //taskStop = DateTime.Now.ToString(); rc = Save(); if (rc >= 0) { taskProcess.StartInfo.RedirectStandardOutput = true; taskProcess.StartInfo.RedirectStandardError = true; taskProcess.OutputDataReceived += new DataReceivedEventHandler(taskProcess_stdout_Handler); taskProcess.ErrorDataReceived += new DataReceivedEventHandler(taskProcess_stderr_Handler); if (taskProcess.Start()) { taskPID = taskProcess.Id; Save(); TaskLogger(2616, 0, string.Format("Task #{0} Started: {1} {2} {3}.", taskSerial, formatFileName, formatParms, path)); taskProcess.BeginOutputReadLine(); taskProcess.BeginErrorReadLine(); } else { TaskLogger(2624, 0, string.Format("Task #{0} NOT Started: {1} {2} {3}.", taskSerial, formatFileName, formatParms, path)); rc = -99; } } else { XLogger(2617, 0, string.Format("XTRMTask.Save() Failed for Task #{1}; rc= #{0}; Task Not Started.", rc, taskSerial)); } } catch (Exception ex) { TaskLogger(2625, 0, string.Format("Task #{0} NOT Started: {1} {2} {3}.", taskSerial, formatFileName, formatParms, path)); taskStatus = 99; taskResult = -1; Save(); aTimer.Close(); taskProcess.OutputDataReceived -= taskProcess_stdout_Handler; taskProcess.ErrorDataReceived -= taskProcess_stderr_Handler; taskProcess.Close(); XLogger(2618, -1, string.Format("Process Could Not Start; Cleaned Up; Serial={0}; Message={1}", taskSerial, ex.Message)); rc = -99; } return rc; }
public void submit(byte[] bytes, UdpUser socket) { SlidingWindow window = new SlidingWindow(); int extraBytes = bytes.Length % 1024; int loop = bytes.Length / 1024; //wait for reply messages from server and send them to console Task.Factory.StartNew(async () => { while (true) { var received = await socket.Receive(); //lock (window) { if (received.packet.AckNumber == window.Window.Peek().SequenceNumber) { window.Forward(); window.LastAck = received.packet.AckNumber; Console.WriteLine(String.Format((received.packet.AckNumber / (Decimal)(loop + 1)).ToString("P", CultureInfo.InvariantCulture))); } } } }); for (int i = 0; i <= loop; i++) { Packet packet = new Packet(); if (i == loop) { packet = new Packet(loop + 1, 0, true, false, extraBytes, Extensions.SubArray(bytes, 1024 * (loop), extraBytes)); } else { packet = new Packet(i + 1, 0, false, false, Convert.ToInt32(1024), Extensions.SubArray(bytes, 1024 * i, 1024)); } socket.Send(packet.BuildPacket()); Timer timer = new Timer(1000); timer.Elapsed += OnTimedEvent; timer.Start(); while (!window.CanForward && timer.Enabled == true) { } if (timer.Enabled == false) { i = window.Window.Peek().SequenceNumber - 2; //i = i - 5; //if (i < -1) { i = -1; } } else { lock (window) { if ((window.Window.Count == 0) || (packet.SequenceNumber > window.Window.Min().SequenceNumber)) { window.InsertPacket(packet); } } } timer.Close(); } }
public void HandlePacket(GSPacketIn packet) { if (packet == null || m_client == null) return; int code = packet.ID; Statistics.BytesIn += packet.PacketSize; Statistics.PacketsIn++; SavePacket(packet); IPacketHandler packetHandler = null; if (code < m_packetHandlers.Length) { packetHandler = m_packetHandlers[code]; } else if (log.IsErrorEnabled) { log.ErrorFormat("Received packet code is outside of m_packetHandlers array bounds! " + m_client); log.Error(Marshal.ToHexDump( String.Format("===> <{2}> Packet 0x{0:X2} (0x{1:X2}) length: {3} (ThreadId={4})", code, code ^ 168, (m_client.Account != null) ? m_client.Account.Name : m_client.TcpEndpoint, packet.PacketSize, Thread.CurrentThread.ManagedThreadId), packet.ToArray())); } // make sure we can handle this packet at this stage var preprocess = PacketPreprocessing.CanProcessPacket(m_client, packet); if(!preprocess) { // this packet can't be processed by this client right now, for whatever reason return; } if (packetHandler != null) { Timer monitorTimer = null; if (log.IsDebugEnabled) { try { monitorTimer = new Timer(10000); m_activePacketHandler = packetHandler; m_handlerThreadID = Thread.CurrentThread.ManagedThreadId; monitorTimer.Elapsed += HandlePacketTimeout; monitorTimer.Start(); } catch (Exception e) { if (log.IsErrorEnabled) log.Error("Starting packet monitor timer", e); if (monitorTimer != null) { monitorTimer.Stop(); monitorTimer.Close(); monitorTimer = null; } } } #if LOGACTIVESTACKS //Put the current thread into the active thread list! //No need to lock the hashtable since we created it //synchronized! One reader, multiple writers supported! m_activePacketThreads.Add(Thread.CurrentThread, m_client); #endif long start = Environment.TickCount; try { packetHandler.HandlePacket(m_client, packet); } catch (Exception e) { if (log.IsErrorEnabled) { string client = (m_client == null ? "null" : m_client.ToString()); log.Error( "Error while processing packet (handler=" + packetHandler.GetType().FullName + " client: " + client + ")", e); } } #if LOGACTIVESTACKS finally { //Remove the thread from the active list after execution //No need to lock the hashtable since we created it //synchronized! One reader, multiple writers supported! m_activePacketThreads.Remove(Thread.CurrentThread); } #endif long timeUsed = Environment.TickCount - start; if (monitorTimer != null) { monitorTimer.Stop(); monitorTimer.Close(); } m_activePacketHandler = null; if (timeUsed > 1000) { string source = ((m_client.Account != null) ? m_client.Account.Name : m_client.TcpEndpoint); if (log.IsWarnEnabled) log.Warn("(" + source + ") Handle packet Thread " + Thread.CurrentThread.ManagedThreadId + " " + packetHandler + " took " + timeUsed + "ms!"); } } }
private void DoPublish(string subject, Message message, uint delay = 0) { if (Message.RECEIVE_ONLY == subject) { throw new InvalidOperationException(Resources.NatsMessagingProvider_PublishReceiveOnlyMessage); } log.Debug(Resources.NatsMessagingProvider_PublishMessage_Fmt, subject, delay, message); string formattedMessage = NatsCommand.FormatPublishMessage(subject, message); log.Trace(Resources.NatsMessagingProvider_LogSent_Fmt, formattedMessage); if (delay == 0) { Write(formattedMessage); } else { Timer delayTimer = null; try { delayTimer = new Timer(delay) { AutoReset = false }; delayTimer.Elapsed += (object sender, ElapsedEventArgs args) => Write(formattedMessage); delayTimer.Enabled = true; delayTimer = null; } finally { if (delayTimer != null) { delayTimer.Close(); } } } }
public void EnterGameModus() { // Generate the map. mapController.GenerateMap(); // Render the map. view.RenderGameScreen(mapController.map); // Start the interval timer. intervalTimer = new Timer(interval); intervalTimer.Elapsed += OnInterval; intervalTimer.AutoReset = true; intervalTimer.Enabled = true; // Loop through input bool quit = false; while (!quit) { ConsoleKeyInfo key = Console.ReadKey(false); // Get string from user switch (key.KeyChar) { case '1': case '2': case '3': case '4': case '5': break; case 'q': quit = true; break; default: view.RenderInvalidInputWarning(key.KeyChar); break; } } // Loop has been ended so the user has quitted. End the game. // Kill the timer. intervalTimer.Enabled = false; intervalTimer.Close(); intervalTimer = null; view.RenderEndScreen(); }
private void CommonTests (Timer t) { Assert.IsTrue (t.AutoReset, "AutoReset"); t.AutoReset = false; Assert.IsFalse (t.Enabled, "Enabled"); t.Enabled = true; Assert.IsNull (t.Site, "Site"); t.Site = null; Assert.IsNull (t.SynchronizingObject, "SynchronizingObject"); t.SynchronizingObject = new TestSyncInvoke (); t.Elapsed += new ElapsedEventHandler (Callback); t.Elapsed -= new ElapsedEventHandler (Callback); t.BeginInit (); t.EndInit (); t.Start (); t.Stop (); t.Close (); (t as IDisposable).Dispose (); }
/// <summary> /// Send a Tcp connection request to a new peer. /// </summary> /// <param name="Message">The request message ( byte[] or string in UTF16 format ).</param> /// <param name="PeerIP">The IP address of the new peer.</param> public static void SendConnectionRequest(object Message, string PeerIP) { Thread t = new Thread(new ParameterizedThreadStart(delegate { if (Message.GetType().ToString() != "System.String" && Message.GetType().ToString() != "System.Byte[]") { throw new System.ArgumentException("The message format is invalid", "Message"); } // if necessary converts the UTF16 to Byte[] if (Message.GetType().ToString() == "System.String") { Message = ASCIIEncoding.Unicode.GetBytes((string)Message); } try { // connect to peer TcpClient client = new TcpClient(); client.Connect(PeerIP.Split(':')[0], int.Parse(PeerIP.Split(':')[1])); // get stream NetworkStream stream = client.GetStream(); // send the request stream.Write((byte[])Message, 0, ((byte[])Message).Length); // wait a reply System.Timers.Timer timer = new System.Timers.Timer(15000); timer.Elapsed += new ElapsedEventHandler(delegate { Thread.CurrentThread.Abort(); }); timer.Enabled = true; byte[] reply_byte = new byte[3072]; stream.Read(reply_byte, 0, reply_byte.Length); string reply = ASCIIEncoding.Unicode.GetString(reply_byte); string[] sub_reply = reply.Split('\n'); // if the peer have accepted the connection request... if (sub_reply[0].Substring(0, 4) == "Nova" && sub_reply[1].Substring(0, 10) == "CONNECT_OK") { Debug.WriteLine("Connection established with " + PeerIP, "Connection established"); // create a new PeersList.Peer() PeersList.Peer peer = new PeersList.Peer(); peer.IP = PeerIP; peer.Client = client; peer.Stream = stream; peer.ID = ""; // add the peer in the PeersList() PeersList.AddPeer(peer); } else { stream.Close(); client.Close(); } timer.Close(); } catch { Debug.WriteLine("A message hasn't been sent, probably the peer is offline or disconnected", "Error"); } })); t.Name = "MessageSender_Request_Connection_Sending"; t.IsBackground = true; t.Start(); }