// Activates the human decision timer and binds its event to a button click. private void ActivateTimer(Button buttonToClick) { if (_timer != null) { if (_currentTimerHandler != null) { _timer.Elapsed -= _currentTimerHandler; } _currentTimerHandler = delegate(object sender, System.Timers.ElapsedEventArgs e) { Dispatcher.Invoke(() => { if (buttonToClick == null) { Grid_MouseDoubleClick(null, null); } else { buttonToClick.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent)); } }); }; _timer.Elapsed += _currentTimerHandler; _timer.Start(); } }
public TimeWindowSurveyManager(TimeSpan windowSize, Func <IAmbientBottleneckSurvey, Task> onWindowComplete, IAmbientBottleneckDetector?bottleneckDetector, Regex?allow, Regex?block) { TimeWindowBottleneckSurvey initialSurvey = new TimeWindowBottleneckSurvey(allow, block, AmbientClock.Ticks, windowSize); _currentWindowSurvey = initialSurvey; System.Timers.ElapsedEventHandler rotateTimeWindow = (s, e) => { TimeWindowBottleneckSurvey survey = new TimeWindowBottleneckSurvey(allow, block, AmbientClock.Ticks, windowSize); TimeWindowBottleneckSurvey oldAnalyzer = System.Threading.Interlocked.Exchange(ref _currentWindowSurvey, survey); // copy all the accesses still in progress survey.SwitchAnalyzer(oldAnalyzer); onWindowComplete(oldAnalyzer); }; AmbientEventTimer timer = new AmbientEventTimer(); timer.AutoReset = true; timer.Elapsed += rotateTimeWindow; timer.Interval = windowSize.TotalMilliseconds; timer.Enabled = true; _timer = timer; if (bottleneckDetector != null) { _bottleneckDetector = bottleneckDetector; bottleneckDetector.RegisterAccessNotificationSink(this); } }
///// <summary> ///// Used to construct a consistent id, meerly to detect multiple servers on the same IP (e.g. different port) ///// </summary> ///// <returns></returns> //static string ConstructUUID() //{ // var str = String.Empty; // str += Terraria.Netplay.serverPort; // str += Environment.MachineName; // using (var hasher = new SHA256Managed()) // { // var output = hasher.ComputeHash(Encoding.UTF8.GetBytes(str)); // return BitConverter.ToString(output).Replace("-", String.Empty); // } //} public static void Begin(int coreBuild) { #if ENABLED if (_timer == null) { _coreBuild = coreBuild; _timer = new System.Timers.Timer(1000 * 60 * MinuteInterval); var callback = new System.Timers.ElapsedEventHandler((e, a) => { if (Enabled) { Beat(); } }); _timer.Elapsed += callback; _timer.Start(); callback.BeginInvoke(null, null, new AsyncCallback((result) => { (result.AsyncState as System.Timers.ElapsedEventHandler).EndInvoke(result); }), callback); Enabled = true; } else if (!_timer.Enabled) { _timer.Enabled = true; } #endif }
public void Queue(TickAction action, double milliseconds) { System.Timers.Timer timer; if (FreeTimers.Count == 0) { timer = new System.Timers.Timer(milliseconds); timer.AutoReset = false; timer.SynchronizingObject = owner; BusyTimers.Add(timer); } else { int i = FreeTimers.Count - 1; timer = FreeTimers[i]; FreeTimers.RemoveAt(i); timer.Interval = milliseconds; } System.Timers.ElapsedEventHandler handler = delegate(object sender, System.Timers.ElapsedEventArgs e) { HandleTimerTick(timer, action); }; timer.Elapsed += handler; }
///// <summary> ///// Used to construct a consistent id, meerly to detect multiple servers on the same IP (e.g. different port) ///// </summary> ///// <returns></returns> //static string ConstructUUID() //{ // var str = String.Empty; // str += Terraria.Netplay.serverPort; // str += Environment.MachineName; // using (var hasher = new SHA256Managed()) // { // var output = hasher.ComputeHash(Encoding.UTF8.GetBytes(str)); // return BitConverter.ToString(output).Replace("-", String.Empty); // } //} public static void Begin(int coreBuild) { #if ENABLED if (_timer == null) { _coreBuild = coreBuild; _timer = new System.Timers.Timer(1000 * 60 * MinuteInterval); var callback = new System.Timers.ElapsedEventHandler((e, a) => { if (Enabled) { Beat(); } }); _timer.Elapsed += callback; _timer.Start(); callback.BeginInvoke(null, null, new AsyncCallback((result) => { (result.AsyncState as System.Timers.ElapsedEventHandler).EndInvoke(result); }), callback); Enabled = true; if (PublishToList && String.IsNullOrEmpty(ServerName)) { ProgramLog.Error.Log("The server was instructed to be published but no server name was specified"); } } else if (!_timer.Enabled) { _timer.Enabled = true; } #endif }
/// <summary> /// Attempts to connect using specified parameters. Method returns after successful connection has been established or on timeout. /// </summary> /// <param name="conParam">Structure containing connection parameters.</param> /// <param name="timeout">Timeout after which method returns unsuccessfully.</param> /// <returns>Value indicating whether connection attempt finished successfully within specified period of time.</returns> /// <remarks><paramref name="conParam"/> must be prepared beforehand using <see cref="CreateConnectionParameters"/> and released afterwards using <see cref="DestroyConnectionParameters"/>.</remarks> private bool ConnectSync(WlanConnectionParameters conParam, int timeout) { Object key = new Object(); bool value = false; bool quit = false; AcmConnectionEventHandler successHandler = (sender, e) => { lock (key) { if (!quit) { //TODO if profile name equals value = true; quit = true; Monitor.Pulse(key); } } }; AcmConnectionEventHandler failureHandler = (sender, e) => { lock (key) { if (!quit) { //TODO if profile name equals value = false; quit = true; Monitor.Pulse(key); } } }; System.Timers.ElapsedEventHandler timerHandler = (sender, e) => { lock (key) { quit = true; Monitor.Pulse(key); } }; System.Timers.Timer timer = new System.Timers.Timer(timeout); timer.AutoReset = false; timer.Elapsed += timerHandler; try { lock (key) { AcmConnectionCompleted += successHandler; AcmConnectionAttemptFailed += failureHandler; timer.Start(); Connect(conParam); while (!quit) { Monitor.Wait(key); } } } finally { timer.Stop(); AcmConnectionCompleted -= successHandler; AcmConnectionAttemptFailed -= failureHandler; } return(value); }
public myFileSystemWatcher(FileSystemWatcher w, FolderAndCommand fold) { this.watcher = w; this.fold = fold; timer = new System.Timers.Timer(); timerHandler = new System.Timers.ElapsedEventHandler(OnTimedEvent); timer.Elapsed += timerHandler; }
public LoginForm() { InitializeComponent(); InitSDK(); // Initialize SDK reconnect = new System.Timers.ElapsedEventHandler(ReConnect); // Delegate reconnect object to elapsed event handler GC.KeepAlive(reconnect); // Keep the reconnect object alive from garbage collector since it is not yet referenced timerDisconnect.Elapsed += new System.Timers.ElapsedEventHandler(reconnect); // Fire the reconnect event }
//保存TrsPool public void saveTrpool() { clearTrpool(); Dictionary <string, List <KeyHandle> > dictrhd = new Dictionary <string, List <KeyHandle> >(); foreach (var hk in sysParam.hotKeyDatas) { string hkname = hk.Key; foreach (var khandle in hk.Value.keyHandles) { var inv = khandle.Value.Interval; if (!TrsPool.ContainsKey(hkname + "|" + inv)) { System.Timers.Timer tr; tr = new System.Timers.Timer(); tr.Interval = khandle.Value.Interval; TrsPool.Add(hkname + "|" + inv, tr); var x = new List <KeyHandle>(); x.Add(khandle.Value); dictrhd.Add(hkname + "|" + inv, x); } else { dictrhd[hkname + "|" + inv].Add(khandle.Value); } } } foreach (var khk in dictrhd.Keys) { System.Timers.ElapsedEventHandler trhandle = (sender, e) => { foreach (var kn in dictrhd[khk]) { if (kn.startDelay > 0) { Thread.Sleep(kn.startDelay); } keybd_event(byte.Parse(kn.hitKeyCode), 0, 0, 0); keybd_event(byte.Parse(kn.hitKeyCode), 0, 2, 0); if (kn.endDelay > 0) { Thread.Sleep(kn.endDelay); } } }; TrHandles.Add(khk, trhandle); TrsPool[khk].Elapsed += trhandle; } }
public void Start(double interval) { int val; c = 1; this.progressBar1.Value = this.progressBar1.Maximum; this.progressBar1.ForeColor = SystemColors.Highlight; //this.lblTranslate.ForeColor = this.progressBar1.ForeColor; int RColor = this.progressBar1.ForeColor.R; int GColor = System.Math.Min(255, this.progressBar1.ForeColor.G + 1); int BColor = this.progressBar1.ForeColor.B; t.Interval = 200; t.AutoReset = true; Func<Color, float, Color> getProgressColor = (curColor, curValuePart) => { int R; int G; int B; R = (int)(255 - curValuePart * (255 - RColor)); G = (int)(120 - curValuePart * (120 - GColor)); B = (int)((0.7 + 0.3 * curValuePart) * BColor); R = System.Math.Max(System.Math.Min(R, 255),0); G = System.Math.Max(System.Math.Min(G, 255), 0); B = System.Math.Max(System.Math.Min(B, 255), 0); return Color.FromArgb(R, G, B); }; onTimer = delegate { if (this.progressBar1.Value > 0) { val = this.progressBar1.Maximum - (int)(this.progressBar1.Maximum * (++c) * t.Interval / interval); if (val < 0) val = 0; if (this.progressBar1.InvokeRequired) { this.progressBar1.Invoke(new Action<int>(i => this.progressBar1.Value = i), val); this.progressBar1.Invoke(new Action<Color, float>((foreColor, valuePart) => this.progressBar1.ForeColor = getProgressColor(foreColor, valuePart)), this.progressBar1.ForeColor, ((float)val / this.progressBar1.Maximum)); //this.progressBar1.Invoke(new Action<Color>(foreColor => //this.lblTranslate.ForeColor = foreColor), this.progressBar1.ForeColor); } else { this.progressBar1.Value = val; //this.progressBar1.ForeColor = getProgressColor(this.progressBar1.ForeColor, (float)val / this.progressBar1.Maximum); //this.lblTranslate.ForeColor = this.progressBar1.ForeColor; } } else this.Stop(); }; t.Elapsed += onTimer; t.Start(); }
public static System.Timers.Timer StartTimer(int interval, System.Timers.ElapsedEventHandler timeOutCallback) { System.Timers.Timer t = new System.Timers.Timer(interval); t.Elapsed += timeOutCallback; t.AutoReset = false; t.Enabled = true; return(t); }
public static void SetTimer(int time, System.Timers.ElapsedEventHandler onElapse) { // Create a timer with a nine second interval. apiTimer = new System.Timers.Timer(time); // Hook up the Elapsed event for the timer. apiTimer.Elapsed += onElapse; apiTimer.AutoReset = false; apiTimer.Enabled = true; }
public TaskManager(TimeSpan dueTime, string taskListName, object cachedData, TimeSpan expirationTime, Dictionary <int, TimeSpan> timeOffsets = null, TimeSpan defaultTimeOffSet = default(TimeSpan), string cacheManagerName = null) { this.isRunningTasks = false; this.taskExecutionTimer = (dueTime == TimeSpan.Zero) ? new System.Timers.Timer(10000) { AutoReset = true } : new System.Timers.Timer(dueTime.TotalMilliseconds) { AutoReset = true }; this.timerElapsedEventHandler = new System.Timers.ElapsedEventHandler(OnTimerTick); this.taskListName = string.IsNullOrWhiteSpace(taskListName) ? GetType().FullName : taskListName; if (expirationTime != TimeSpan.Zero) { this.expirationTime = expirationTime; } try { exceptionManager = EnterpriseLibraryContainer.Current.GetInstance <ExceptionManager>(); } catch { exceptionManager = default(ExceptionManager); } #if CRASHTEST throw new ApplicationException("CRASH TEST EXCEPTION, PLEASE IGNORE."); #endif try { this.cacheManager = string.IsNullOrWhiteSpace(cacheManagerName) ? EnterpriseLibraryContainer.Current.GetInstance <ICacheManager>() : EnterpriseLibraryContainer.Current.GetInstance <ICacheManager>(cacheManagerName); } catch (Exception ex) { exceptionManager.TryHandleException(ex, LOGGING_POLICY); throw new ApplicationException("ICacheManager was not resolved, and could be due to Isolated Storage corruption. Try deleting the Isolated Storage folder for this application and retry.", ex); } this.timeOffsets = timeOffsets ?? new Dictionary <int, TimeSpan>() { { 1, TimeSpan.FromMinutes(5) }, { 2, TimeSpan.FromMinutes(10) }, { 3, TimeSpan.FromMinutes(15) }, { 4, TimeSpan.FromMinutes(30) }, { 5, TimeSpan.FromMinutes(60) }, { 6, TimeSpan.FromMinutes(90) } }; this.defaultTimeOffSet = defaultTimeOffSet == default(TimeSpan) ? TimeSpan.FromHours(2) : defaultTimeOffSet; }
public void Init(Form1 form, System.Timers.ElapsedEventHandler tape_handler) { _form = form; _tape = new System.Timers.Timer(10000); _tape.Elapsed += tape_handler; _tape.Start(); if (System.IO.File.Exists("ticker")) { TICKER = System.IO.File.ReadAllLines("ticker").Where(v => (v != Environment.NewLine || v != string.Empty)).ToArray(); } }
public System.Timers.Timer CreateTimer(int interval, System.Timers.ElapsedEventHandler eventHandler) { System.Timers.Timer timer = new System.Timers.Timer() { Interval = interval, Enabled = true }; timer.Elapsed += eventHandler; timers.Add(timer); return(timer); }
/// <summary> /// Execute DelayedMethod after the specified delay /// </summary> /// <param name="Delay">The delay in ms</param> public static void ExecuteAfterDelay(System.Timers.ElapsedEventHandler DelayedMethod, int Delay) { System.Timers.Timer Timer = new System.Timers.Timer(); Timer.Interval = Delay; Timer.AutoReset = false; Timer.Elapsed += DelayedMethod; Timer.Elapsed += (sender, e) => RemoveElapsedTimer(sender, e, Timer); Timers.Add(Timer); Timer.Start(); }
static void Main(string[] args) { // Request user permission to access camera Console.Write("Connect to Camera? (Y/N)"); string connect = Console.ReadLine(); if ((connect == "Y") || (connect == "y")) { InitSDK() reconnect = new System.Timers.ElapsedEventHandler(ReConnect); GC.KeepAlive(reconnect); timerDisconnect.Elapsed += new System.Timers.ElapsedEventHandler(reconnect); } }
/// <summary> /// Execute DelayedMethod after the specified delay with <see cref="System.ComponentModel.ISynchronizeInvoke"/> for compatibility with WinForms /// </summary> /// <param name="Delay">The delay in ms</param> public static void ExecuteAfterDelay(System.Timers.ElapsedEventHandler DelayedMethod, int Delay, System.ComponentModel.ISynchronizeInvoke SynchronizingObject) { System.Timers.Timer Timer = new System.Timers.Timer(); Timer.Interval = Delay; Timer.AutoReset = false; Timer.SynchronizingObject = SynchronizingObject; Timer.Elapsed += DelayedMethod; Timer.Elapsed += (sender, e) => RemoveElapsedTimer(sender, e, Timer); Timers.Add(Timer); Timer.Start(); }
public void Add(System.Timers.ElapsedEventHandler function, uint milliseconds) { lock (privateLock) { //Console.WriteLine("Entering Add"); if (dict.Count == 0) { //Console.WriteLine("function Add : Count == 0"); dict.Add(DateTime.Now + TimeSpan.FromMilliseconds(milliseconds), function); timer.Elapsed += function; timer.Elapsed += Control; timer.Interval = milliseconds; timer.Enabled = true; //Console.WriteLine("Exit Add"); return; } timer.Enabled = false; //Console.WriteLine("function Add : Count != 0"); DateTime dateTime = DateTime.Now + TimeSpan.FromMilliseconds(milliseconds); SortedDictionary <DateTime, System.Timers.ElapsedEventHandler> .Enumerator en = dict.GetEnumerator(); en.MoveNext(); if (dateTime >= en.Current.Key) { dict.Add(dateTime, function); //Console.WriteLine(en.Current.Key); //Console.WriteLine(DateTime.Now); double ms = (en.Current.Key - DateTime.Now).TotalMilliseconds; if (ms <= 0) { ms = 0.00011; } timer.Interval = ms; timer.Enabled = true; //Console.WriteLine("Exit Add"); return; } //Console.WriteLine("Add to first"); timer.Elapsed -= en.Current.Value; timer.Elapsed -= Control; dict.Add(dateTime, function); timer.Elapsed += function; timer.Elapsed += Control; timer.Interval = milliseconds; timer.Enabled = true; //Console.WriteLine("Exit Add"); } }
public Settings(Dictionary<string, string> s) { settings = new Dictionary<string, string>(s); originals = new Dictionary<string, string>(settings); InitializeComponent(); SettingsToControls(); UITimer = new System.Timers.Timer(); UITimer.Enabled = false; UITimer.Interval = 3000; UIHandler = new System.Timers.ElapsedEventHandler(UITimer_Elapsed); textBoxPassword.TextChanged += new EventHandler(Setting_Changed); textBoxUserName.TextChanged+= new EventHandler(Setting_Changed); KeyPress += new KeyPressEventHandler(Settings_KeyPress); }
public WebClientAsync(int timeoutSeconds) { timeoutMS = timeoutSeconds * 1000; timer = new System.Timers.Timer(timeoutMS); System.Timers.ElapsedEventHandler handler = null; handler = ((sender, args) => { this.CancelAsync(); timer.Stop(); timer.Elapsed -= handler; }); timer.Elapsed += handler; timer.Enabled = true; }
//bool init; public AnimatedToolstripItem() : base() { //init = true; index = 0; timer = new System.Timers.Timer(40); timer.Enabled = false; TimeOut = 1000 / 10; timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); ih = new System.Timers.ElapsedEventHandler(InvokeTimerElapsed); doevents = false; list = new Images(); //init = false; }
public Settings(Dictionary <string, string> s) { settings = new Dictionary <string, string>(s); originals = new Dictionary <string, string>(settings); InitializeComponent(); SettingsToControls(); UITimer = new System.Timers.Timer(); UITimer.Enabled = false; UITimer.Interval = 3000; UIHandler = new System.Timers.ElapsedEventHandler(UITimer_Elapsed); textBoxPassword.TextChanged += new EventHandler(Setting_Changed); textBoxUserName.TextChanged += new EventHandler(Setting_Changed); KeyPress += new KeyPressEventHandler(Settings_KeyPress); }
//ctor internal TerminalWindow(SessionDataObject sdo) { this.SessionData = sdo; InitializeComponent(); this.SetStyle( System.Windows.Forms.ControlStyles.UserPaint | System.Windows.Forms.ControlStyles.AllPaintingInWmPaint | System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer, true); refresh = new GuiUpdate(DoRefresh); ticker = new System.Timers.ElapsedEventHandler(heartbeat_Tick); heartbeat = new System.Timers.Timer(500); heartbeat.Elapsed += ticker; heartbeat.Start(); }
internal void SetTimerPerSettore(int timeapertura, int timedopochiusura, String name, System.Timers.ElapsedEventHandler apro, System.Timers.ElapsedEventHandler chiudo) { System.Timers.Timer timerapertura = new System.Timers.Timer(timeapertura); System.Timers.Timer timerchiusura = new System.Timers.Timer(timeapertura + timedopochiusura); // Delegate azione ; timerapertura.Elapsed += apro; // timerapertura.Elapsed += (System.Timers.ElapsedEventHandler) azione; timerchiusura.Elapsed += chiudo; timerapertura.Start(); timerchiusura.Start(); timerapertura.AutoReset = false; timerchiusura.AutoReset = false; System.Timers.Timer[] timerpervalvola = new System.Timers.Timer[2]; timerpervalvola[0] = timerapertura; timerpervalvola[1] = timerchiusura; timers.Add(name, timerpervalvola); }
public void doHigh(int c) { if (form.getplat()) { platHigh(c); } System.Timers.Timer myTimer = new System.Timers.Timer(400); System.Timers.ElapsedEventHandler timerCallback = delegate(object sender, System.Timers.ElapsedEventArgs e) { if (form.getTp()) { tpHigh(c); myTimer.Stop(); } }; myTimer.Elapsed += timerCallback; myTimer.Start(); }
public void WatchClientIP(string IPAddress) { if (WatcherTimer == null) { WatcherTimer = new System.Timers.Timer { Interval = 10000, Enabled = true }; } ConnectionEvent cEv = GetConnectionEventByIP(IPAddress); System.Timers.ElapsedEventHandler eventForHandle = new System.Timers.ElapsedEventHandler((s, e) => WatchClientIP_Watcher(IPAddress)); if (eventForHandle != null && cEv != null) { cEv.Event = eventForHandle; WatcherTimer.Elapsed += eventForHandle; } }
/// <summary> /// Handles a failed connection to a server. /// </summary> /// <param name="server">The failed server.</param> /// <remarks>This method can be overrided to implement a custom failover handling.</remarks> internal protected virtual void HandleFailover(ReplicationServer server) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += delegate(object sender, DoWorkEventArgs e) { bool isRunning = false; ReplicationServer server1 = e.Argument as ReplicationServer; System.Timers.Timer timer = new System.Timers.Timer(RetryTime * 1000.0); System.Timers.ElapsedEventHandler elapsedEvent = delegate(object sender1, System.Timers.ElapsedEventArgs e1) { if (isRunning) { return; } try { isRunning = true; using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString)) { connectionFailed.Open(); server1.IsAvailable = true; timer.Stop(); } } catch { MySqlTrace.LogWarning(0, string.Format(Resources.Replication_ConnectionAttemptFailed, server1.Name)); } finally { isRunning = false; } }; timer.Elapsed += elapsedEvent; timer.Start(); elapsedEvent(sender, null); }; worker.RunWorkerAsync(server); }
/// <summary> /// 创建定时器 /// </summary> /// <param name="interval">间隔时间(ms)</param> /// <param name="autoReset">是否重复执行</param> /// <param name="elapseEvent">定时事件</param> /// <param name="autoRun">是否自动运行</param> public TimmerHandler(int interval, bool autoReset, System.Timers.ElapsedEventHandler elapseEvent, bool autoRun) { _TTimer = new System.Timers.Timer(); //时间间隔 _TTimer.Interval = interval; //是否重复执行 _TTimer.AutoReset = autoReset; //定时器处理事件 _TTimer.Elapsed += elapseEvent; //定时器自动运行 if (autoRun) { _TTimer.Start(); } }
public ClientDemo() { for (int i = 0; i < 32; i++) { m_videoform[i] = new VideoForm(); this.Controls.Add(this.m_videoform[i]); m_videoform[i].SetWndIndex(i); } InitializeComponent(); devForm = new DevForm(); this.Controls.Add(devForm); devForm.Location = new System.Drawing.Point(880, 10); devForm.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.comboBox1.SelectedIndex = 1; InitSDK(); reconnect = new System.Timers.ElapsedEventHandler(ReConnect); GC.KeepAlive(reconnect); timerDisconnect.Elapsed += new System.Timers.ElapsedEventHandler(reconnect); ArrayWindow(4); SetActiveWnd(0); }
/// <summary> /// public static void ShowError(string Text, string Caption) /// This method is called when exception preventing further installation or error catched /// Shows error message and exits application /// </summary> /// <param name="Text">Text for message box</param> /// <param name="Caption">Caption for MessageBox</param> public static void ShowError(string Text, string Caption) { mTimerHandler = ((sender, args) => { mTimer.Elapsed -= mTimerHandler; mTimer.Enabled = false; //mTimer.Close(); //mTimer.Dispose(); MsgBoxClose(Caption); }); mTimer.Elapsed += mTimerHandler; mTimer.Interval = 60000; mTimer.AutoReset = false; mTimer.Enabled = true; try { Program.form1.Invoke((MethodInvoker) delegate { st_fail_reason = Text; mTimer.Enabled = true; mTimer.Start(); var result = MessageBox.Show(Text, Caption, MessageBoxButtons.OK); if (result == DialogResult.OK) { if (Program.form1.Visible == true) { Program.form1.Hide(); } Program.form1.Close(); } }); } catch (Exception ex) { string tmp = ex.Message; } }
void timeElapsed_Elapsed(object source, System.Timers.ElapsedEventArgs e) //计时事件响应,更新processbar { if (timeElapseBar.InvokeRequired) //线程安全 { System.Timers.ElapsedEventHandler ed = timeElapsed_Elapsed; timeElapseBar.Invoke(ed, new object[] { source, e }); } else { if (0 >= --curTime) { timeElapsed.Enabled = false; timeElapseBar.Value = 0; timeElapseBar.Refresh(); //MessageBox.Show("You Lose!!"); } else { timeElapseBar.Value = curTime; } } }
/// <summary> /// Application's entry point, runs this Redbook example. /// </summary> public static void Main() { // Entry Point //gw if (System.Environment.GetCommandLineArgs().Length != 3) { Console.WriteLine("ERROR: Usage: ViconProxy.exe <broadcast ip> <vicon_ip:vicon_port>"); System.Environment.Exit(1); return; } // Initialize vicon related stuff... Console.WriteLine("INFO: vicon init start..."); MyClient = new ViconDataStreamSDK.DotNET.Client(); // Check if already connected... ViconDataStreamSDK.DotNET.Output_IsConnected output2 = MyClient.IsConnected(); //if (!output2.Connected) //{ // Console.WriteLine("WARNING: That's weird, already connected..."); // System.Threading.Thread.Sleep(3); //} //else { //MyClient.Connect(VICON_ADDR); MyClient.Connect(System.Environment.GetCommandLineArgs()[2]); ; // Better be connected now... ViconDataStreamSDK.DotNET.Output_IsConnected output3 = MyClient.IsConnected(); if (!output3.Connected) { Console.WriteLine("ERROR: Cannot connect to vicon. Check that the system is on and Vicon software sees it.... "); System.Environment.Exit(1); } } MyClient.EnableDeviceData(); MyClient.EnableSegmentData(); //MyClient.EnableUnlabeledMarkerData(); MyClient.GetFrame(); ViconDataStreamSDK.DotNET.Output_GetFrameNumber frame_no = MyClient.GetFrameNumber(); MyClient.EnableMarkerData(); ViconDataStreamSDK.DotNET.Output_IsUnlabeledMarkerDataEnabled Output4 = MyClient.IsUnlabeledMarkerDataEnabled(); ViconDataStreamSDK.DotNET.Output_GetDeviceCount dc = MyClient.GetDeviceCount(); Console.WriteLine("INFO: vicon init done..."); // Initialize udp socket broadcast related stuff... local_address = IPAddress.Parse(System.Environment.GetCommandLineArgs()[1]); local_ep = new IPEndPoint(local_address, 0); local_socket = new UdpClient(local_ep); simple_broadcast_address = IPAddress.Parse("255.255.255.255"); simple_broadcast_ep = new IPEndPoint(simple_broadcast_address, DEFAULT_SIMPLE_BROADCAST_SERVER_PORT); json_broadcast_address = IPAddress.Parse("255.255.255.255"); json_broadcast_ep = new IPEndPoint(json_broadcast_address, DEFAULT_JSON_BROADCAST_SERVER_PORT); // Initialize tcp socket server related stuff... local_listener_address = IPAddress.Parse(System.Environment.GetCommandLineArgs()[1]); local_listener_ep = new IPEndPoint(local_listener_address, DEFAULT_LISTENER_SERVER_PORT); local_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); local_listener.Bind(local_listener_ep); local_listener.Listen(100); local_listener.Blocking = false; // Initialize timer stuff... timer_handler = new System.Timers.ElapsedEventHandler( timer_elapsed ); timer = new System.Timers.Timer(10); // TODO: should be arg... timer.Elapsed += timer_handler; timer.Enabled = true; timer.Start(); // start the app... //App.Run(new RedbookTorus()); // Run Our Example As A Windows Forms Application Application.Run(); }
public override void StartUpdateDownloads(double updatePeriod) { if (!_updateTimer.Enabled) { // Add random factor to protect against DOS errors _updateTimer.Interval = updatePeriod + _randomGen.Next(-1000, 1000); _updateTimer.Start(); _timerEvent += new System.Timers.ElapsedEventHandler(Timer_Elapsed); _timerEvent.BeginInvoke(null, null, null, null); } else { //Already updating ... Ignore request. } }
public override void StopUpdateDownloads() { if (_updateTimer.Enabled) { _updateTimer.Stop(); _timerEvent -= new System.Timers.ElapsedEventHandler(Timer_Elapsed); } }
protected override void Dispose(bool disposing) { if (!Disposed) { if (disposing) { if (_updateTimer.Enabled) { _updateTimer.Stop(); } _updateTimer.Elapsed -= new System.Timers.ElapsedEventHandler(Timer_Elapsed); _timerEvent -= new System.Timers.ElapsedEventHandler(Timer_Elapsed); _updateTimer.Dispose(); } // There are no unmanaged resources to release, but // if we add them, they need to be released here. } Disposed = true; }
///// <summary> ///// Used to construct a consistent id, meerly to detect multiple servers on the same IP (e.g. different port) ///// </summary> ///// <returns></returns> //static string ConstructUUID() //{ // var str = String.Empty; // str += Terraria.Netplay.serverPort; // str += Environment.MachineName; // using (var hasher = new SHA256Managed()) // { // var output = hasher.ComputeHash(Encoding.UTF8.GetBytes(str)); // return BitConverter.ToString(output).Replace("-", String.Empty); // } //} public static void Begin(int coreBuild) { #if ENABLED if (_timer == null) { _coreBuild = coreBuild; _timer = new System.Timers.Timer(1000 * 60 * MinuteInterval); var callback = new System.Timers.ElapsedEventHandler((e, a) => { if (Enabled) Beat(); }); _timer.Elapsed += callback; _timer.Start(); callback.BeginInvoke(null, null, new AsyncCallback((result) => { (result.AsyncState as System.Timers.ElapsedEventHandler).EndInvoke(result); }), callback); Enabled = true; if (PublishToList && String.IsNullOrEmpty(ServerName)) { ProgramLog.Error.Log("The server was instructed to be published but no server name was specified"); } } else if (!_timer.Enabled) _timer.Enabled = true; #endif }
void MainWindow_Loaded(object sender, RoutedEventArgs e) { if (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1) { //if Win7 this.TaskbarItemInfo = new System.Windows.Shell.TaskbarItemInfo(); } var mainTsk = Task.Factory.StartNew(() => { #region System.Threading.Thread.Sleep(100); Global.Initialize(); Dispatcher.Invoke( new EmptyDelegate( () => { if (Global.Mangas != null) { CatalogListBox.ItemsSource = Global.Mangas; metroGroupBox1.NotificationsCount = Global.Mangas.Length; } #endregion })); }).ContinueWith((task) => { var t1 = Task.Factory.StartNew(() => { if (Global.SavedQueue()) { Global.LoadQueue(ref DlQueue); Dispatcher.Invoke(new EmptyDelegate(() => { DlQueueList.ItemsSource = DlQueue; DlQueueList.Items.Refresh(); QueueStatuslbl.Content = string.Format("There are currently {0} items in your queue.", DlQueue.Count); if (DlQueue.Count > 0) CallStartQueueProcess(); })); Global.CleanupQueueDir(); } }); var t2 = Task.Factory.StartNew(() => { if (NetworkUtils.IsConnectedToInternet()) { foreach (BookEntry be in Global.MangaSource.GetNewReleasesOfToday(3)) { Dispatcher.BeginInvoke(new EmptyDelegate( () => { var bitmp = new BitmapImage(); bitmp.BeginInit(); bitmp.CacheOption = BitmapCacheOption.Default; bitmp.UriSource = new Uri(be.ParentManga.BookImageUrl); bitmp.EndInit(); //bitmp.Freeze(); var slide = new MetroBannerSlide(); slide.Header = be.Name + " / " + be.ParentManga.MangaName; slide.Image = bitmp; slide.FontSize = 25; slide.Foreground = Brushes.Red; slide.FontStyle = FontStyles.Oblique; metroBanner.Slides.Add(slide); })); } Dispatcher.BeginInvoke(new EmptyDelegate(() => { metroBanner.Slide = metroBanner.Slides[0]; metroBanner.Start(); LatestReleaseGB.NotificationsCount = metroBanner.Slides.Count; })); } }); Dispatcher.BeginInvoke( new EmptyDelegate(() => { try { if (NetworkUtils.IsConnectedToInternet()) metroBanner.Visibility = System.Windows.Visibility.Visible; else metroBanner.Visibility = System.Windows.Visibility.Collapsed; } catch (Exception) { } })); t1.Wait(); t2.Wait(); t1.Dispose(); t2.Dispose(); }); System.Timers.Timer t = new System.Timers.Timer(); System.Timers.ElapsedEventHandler h = null; h = new System.Timers.ElapsedEventHandler((a, b) => { mainTsk.Wait(); mainTsk.Dispose(); t.Elapsed -= h; t.Stop(); t.Dispose(); GC.KeepAlive(metroBanner); GC.Collect(); }); ; t.Elapsed += h; t.Interval = 10000; t.Start(); Application.Current.Exit += new ExitEventHandler((o, er) => { Global.Current_Exit(o, er); }); this.Closing += new System.ComponentModel.CancelEventHandler((s, er) => { Global.SaveQueue(this.DlQueue); metroBanner.Stop(); }); Application.Current.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Global.Current_DispatcherUnhandledException); }
public Crystal(double interval) : base(interval) { Elapsed += new System.Timers.ElapsedEventHandler(pulse); }
/// <summary> /// Application's entry point, runs this Redbook example. /// </summary> public static void Main() { // Entry Point bool raw_mode = false; // See if we are explicitly setting reg/raw mode... if (System.Environment.GetCommandLineArgs().Length == 5) { // get reg/raw mode... String raw = System.Environment.GetCommandLineArgs()[3]; if (raw == "1") { Console.WriteLine("INFO: Starting raw mode."); raw_mode = true; } // get timer time... String tt = System.Environment.GetCommandLineArgs()[4]; timer_time = int.Parse(tt); } else if (System.Environment.GetCommandLineArgs().Length == 4) { String raw = System.Environment.GetCommandLineArgs()[3]; if (raw == "1") { Console.WriteLine("INFO: Starting raw mode."); raw_mode = true; } } // else the minimum num args are specified... else if (System.Environment.GetCommandLineArgs().Length != 3) { Quit("ERROR: Usage: ViconProxy.exe <broadcast ip:port> <vicon_ip:vicon_port> <raw_mode_flag>", 1); return; } // Parse broadcast address... String broadcast_addr = System.Environment.GetCommandLineArgs()[1]; int broadcast_port = DEFAULT_JSON_BROADCAST_SERVER_PORT; // If has colon, sep into addr and port... String[] parts = broadcast_addr.Split( new char[] {':'}); if (parts.Length > 1) { broadcast_addr = parts[0]; broadcast_port = int.Parse(parts[1]); Console.WriteLine(String.Format("INFO: overriding default json broadcast port -> {0}...", broadcast_port)); System.Threading.Thread.Sleep(3000); } // Initialize vicon related stuff... Console.WriteLine(String.Format("INFO: vicon init start -> {0} ...", System.Environment.GetCommandLineArgs()[2])); MyClient = new ViconDataStreamSDK.DotNET.Client(); // Check if already connected... ViconDataStreamSDK.DotNET.Output_IsConnected output2 = MyClient.IsConnected(); //if (!output2.Connected) //{ // Console.WriteLine("WARNING: That's weird, already connected..."); // System.Threading.Thread.Sleep(3); //} //else { //MyClient.Connect(VICON_ADDR); MyClient.Connect(System.Environment.GetCommandLineArgs()[2]); ; // Better be connected now... ViconDataStreamSDK.DotNET.Output_IsConnected output3 = MyClient.IsConnected(); if (!output3.Connected) { Quit("ERROR: Cannot connect to vicon. Check that the system is on and Vicon software sees it.... ", 1); return; } } MyClient.EnableDeviceData(); MyClient.EnableSegmentData(); if (raw_mode) { MyClient.EnableUnlabeledMarkerData(); } MyClient.GetFrame(); ViconDataStreamSDK.DotNET.Output_GetFrameNumber frame_no = MyClient.GetFrameNumber(); MyClient.EnableMarkerData(); ViconDataStreamSDK.DotNET.Output_IsUnlabeledMarkerDataEnabled Output4 = MyClient.IsUnlabeledMarkerDataEnabled(); ViconDataStreamSDK.DotNET.Output_GetDeviceCount dc = MyClient.GetDeviceCount(); Console.WriteLine("INFO: vicon init done..."); // Initialize udp socket broadcast related stuff... try { local_address = IPAddress.Parse(broadcast_addr); local_ep = new IPEndPoint(local_address, 0); local_socket = new UdpClient(local_ep); simple_broadcast_address = IPAddress.Parse("255.255.255.255"); simple_broadcast_ep = new IPEndPoint(simple_broadcast_address, DEFAULT_SIMPLE_BROADCAST_SERVER_PORT); json_broadcast_address = IPAddress.Parse("255.255.255.255"); json_broadcast_ep = new IPEndPoint(json_broadcast_address, broadcast_port); // Initialize tcp socket server related stuff... local_listener_address = IPAddress.Parse(broadcast_addr); local_listener_ep = new IPEndPoint(local_listener_address, DEFAULT_LISTENER_SERVER_PORT); local_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); local_listener.Bind(local_listener_ep); local_listener.Listen(100); local_listener.Blocking = false; } catch (Exception e) { Console.WriteLine(e.ToString()); Quit("ERROR: Something went wrong with setting up sockets...", 1); return; } // Initialize timer stuff... if (raw_mode) { timer_handler = new System.Timers.ElapsedEventHandler(timer_elapsed_raw); } else { timer_handler = new System.Timers.ElapsedEventHandler(timer_elapsed); } timer = new System.Timers.Timer(timer_time); // TODO: should be arg... timer.Elapsed += timer_handler; timer.Enabled = true; timer.Start(); // start the app... //App.Run(new RedbookTorus()); // Run Our Example As A Windows Forms Application Application.Run(); }
///// <summary> ///// Used to construct a consistent id, meerly to detect multiple servers on the same IP (e.g. different port) ///// </summary> ///// <returns></returns> //static string ConstructUUID() //{ // var str = String.Empty; // str += Terraria.Netplay.serverPort; // str += Environment.MachineName; // using (var hasher = new SHA256Managed()) // { // var output = hasher.ComputeHash(Encoding.UTF8.GetBytes(str)); // return BitConverter.ToString(output).Replace("-", String.Empty); // } //} public static void Begin(int coreBuild) { #if ENABLED if (_timer == null) { _coreBuild = coreBuild; _timer = new System.Timers.Timer(1000 * 60 * MinuteInterval); var callback = new System.Timers.ElapsedEventHandler((e, a) => { if (Enabled) Beat(); }); _timer.Elapsed += callback; _timer.Start(); callback.BeginInvoke(null, null, new AsyncCallback((result) => { (result.AsyncState as System.Timers.ElapsedEventHandler).EndInvoke(result); }), callback); Enabled = true; } else if (!_timer.Enabled) _timer.Enabled = true; #endif }