public BoringCommanderLogic(BoringCommander form) { _form = form; _initBasicState(); System.Threading.Timer t = new System.Threading.Timer(_updConfig); t.Change(50, 50); }
/// <summary> /// アプリケーションドメインホストから停止を通知される. /// </summary> /// <param name="immediate"></param> public void Stop(bool immediate) { // タイマーを解除する. if (_timer != null) { _timer.Dispose(); _timer = null; } // すべてのトレースリスナをクローズする. foreach (TraceListener listener in System.Diagnostics.Trace.Listeners) { try { listener.Close(); } catch { // 無視する. } } // オブジェクトの登録を解除する. HostingEnvironment.UnregisterObject(this); }
private void BtnBrowseImage_Click(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog { Multiselect = false, //Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*", Filter = "JPEG Images (*.jpeg *.jpg)|*.jpeg;*.jpg|Png Images (*.png)|*.png", }; if (ofd.ShowDialog() == true) { try { LoadingInfo.Visibility = System.Windows.Visibility.Visible; focusRectangle.Viewport.Visibility = System.Windows.Visibility.Collapsed; focusRectangle.LoadImageStream(ofd.File.OpenRead(), ZoomInOut); fileInfo = ofd.File; BtnUploadImage.IsEnabled = BtnAdvanceMode.IsEnabled = false; ZoomInOut.IsEnabled = true; System.Threading.Timer timer = new System.Threading.Timer(TimerCallback, new LoadingState() { focusRectangle = focusRectangle, LoadingInfo = LoadingInfo, BtnUploadImage = BtnUploadImage, BtnAdvanceMode = BtnAdvanceMode } as object, 1000, 500); } catch (Exception exception) { Utils.ShowMessageBox("文件无效:" + exception.Message); ZoomInOut.IsEnabled = false; BtnUploadImage.IsEnabled = BtnAdvanceMode.IsEnabled = false; } } }
public FFTDraw() { // Insert initialization code here. this.data = new float[512]; this.updater = new System.Threading.Timer(this.DoFFT); this.updater.Change(0, 50); }
//FiltroMediana filtroLat = new FiltroMediana(10); //FiltroMediana filtroLon = new FiltroMediana(10); //FiltroMediana filtroAlt = new FiltroMediana(10); public AntTracker() { planeStateUpdated = false; terminate = false; antenaTracker = new AntenaTracker(); datosAvion = new AntTrackerDatosAvion(); datosAvion.LoadDefaults(); debug = new AntTrackerDebug(); debug.LoadDefaults(); if (antenaTracker.IsOpen()) { timer = new System.Threading.Timer(TimerTask, this, 1000, 1000 /5); } else if (singleton.Idioma == 0) { MessageBox.Show("No se puede abrir dispositivo AntTracker"); } else { MessageBox.Show("Cannot open AntTracker device"); } }
public Main() { this.InitializeComponent(); this.playlistExtender = new ListViewExtender(this.playlist); // extend 2nd column var buttonAction = new ListViewButtonColumn(this.playlist.Columns.Count - 1); buttonAction.Click += this.PlaySingleAction; buttonAction.FixedWidth = true; this.playlistExtender.AddColumn(buttonAction); this.DragEnter += MainDragEnter; this.DragDrop += MainDragDrop; this.addDialog = new AddDialog(); this.settingsDialog = new Settings(); this.lblVersion.Text = string.Format("Version {0} [[email protected]]", Application.ProductVersion); this.settingSerializer = new DisplaySettingSerializer(); this.playlistSerializer = new PlaylistSerializer(); this.mouseTimer = new System.Threading.Timer(DisplayMousePosition); this.Disposed += Main_Disposed; }
protected override void OnStop() { this.eventLog.WriteEntry("Squid is stopping...", EventLogEntryType.Information); if (timer != null) { timer.Dispose(); timer = null; } if (updateTimer != null) { updateTimer.Dispose(); updateTimer = null; } lock(this.locker) { this.Kill(this.squid); this.squid = null; } var processes = Process.GetProcessesByName("squid"); foreach (var p in processes) { this.Kill(p); } this.eventLog.WriteEntry("Squid stopped.", EventLogEntryType.Information); }
AutoClosingMessageBox(string text, string caption, int timeout) { _caption = caption; _timeoutTimer = new System.Threading.Timer(OnTimerElapsed, null, timeout, System.Threading.Timeout.Infinite); //MessageBox.Show(text, caption); }
public StockPresenterViewModel() { Stocks = GetSavedStocks(); _dataRefreshTimer = new System.Threading.Timer((state) => { _dataRefreshTimer.Change(System.Threading.Timeout.Infinite, _dataRefreshInterval); if (null != Stocks) { lock (Stocks) { foreach (StockViewModel curStock in Stocks) { //assuming it is the first one var infos = Business.Stocks.GetMarketInfo<StockViewModel>(curStock.Symbol); if (infos.Count() > 0) { StockViewModel tmp = infos.First(); curStock.Timestamp = tmp.Timestamp; curStock.MarketPrice = tmp.MarketPrice; } } } } _dataRefreshTimer.Change(_dataRefreshInterval, _dataRefreshInterval); }, null, 0, _dataRefreshInterval); }
internal NodeGroup(RelayNodeGroupDefinition groupDefinition, RelayNodeConfig nodeConfig, ForwardingConfig forwardingConfig) { GroupDefinition = groupDefinition; Activated = groupDefinition.Activated; _clusterByRange = groupDefinition.UseIdRanges; _forwardingConfig = forwardingConfig; NodeSelectionHopWindowSize = groupDefinition.NodeSelectionHopWindowSize; RelayNodeClusterDefinition myClusterDefinition = NodeManager.Instance.GetMyNodeClusterDefinition(); foreach (RelayNodeClusterDefinition clusterDefintion in groupDefinition.RelayNodeClusters) { NodeCluster nodeCluster = new NodeCluster(clusterDefintion, nodeConfig, this, forwardingConfig); if (clusterDefintion == myClusterDefinition) { MyCluster = nodeCluster; } Clusters.Add(nodeCluster); } _nodeReselectTimerCallback = new System.Threading.TimerCallback(NodeReselectTimer_Elapsed); if (_nodeReselectTimer == null) { _nodeReselectTimer = new System.Threading.Timer(_nodeReselectTimerCallback); } _nodeReselectTimer.Change(NodeReselectIntervalMilliseconds, NodeReselectIntervalMilliseconds); QueueTimerCallback = new System.Threading.TimerCallback(QueueTimer_Elapsed); if (QueueTimer == null) { QueueTimer = new System.Threading.Timer(QueueTimerCallback); } QueueTimer.Change(DequeueIntervalMilliseconds, DequeueIntervalMilliseconds); }
public void Start() { HasStarted = false; System.Threading.TimerCallback callback = new System.Threading.TimerCallback(this.Begin); timer = new System.Threading.Timer(callback, null, 1, 1000); return; }
//static long nextTick = DateTime.Now.Ticks; public BusinessGraphicsForm(BusinessGraphicsSourceDesign sourceDesign, Window window) { InitializeComponent(); if (window is ActiveWindow) { wnd = (ActiveWindow)window; BackColor = wnd.BorderColorFrienly; } sourceDesign.Wnd = wnd; sourceDesign.IsPlayerMode = true; _sourceCopy = SourceDesignClone(sourceDesign); this.sourceDesign = sourceDesign; this.sourceDesign.InitializeChart(true); Controls.Clear(); this.sourceDesign.AddChartToContainer(this, wnd); FormClosing += BusinessGraphicsForm_FormClosing; if (sourceDesign.ODBCRefreshInterval > 0) { int time = sourceDesign.ODBCRefreshInterval*1000; if (((BusinessGraphicsResourceInfo) sourceDesign.ResourceDescriptor.ResourceInfo).ProviderType == ProviderTypeEnum.ODBC) refreshTimer = new Timer(RefreshChart, "Timer", time, time); } //начал делать тут проверку, а она оказывается не нужна// //nextTick += time; }
void Work() { LoadFile(); timer = new System.Threading.Timer(Output); timer.Change(0, 1000); }
public FileWatcher(string path, string[] filter) { if (filter == null || filter.Length == 0) { FileSystemWatcher mWather = new FileSystemWatcher(path); mWather.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed); mWather.Deleted += new FileSystemEventHandler(fileSystemWatcher_Changed); mWather.Created += new FileSystemEventHandler(fileSystemWatcher_Changed); mWather.EnableRaisingEvents = true; mWather.IncludeSubdirectories = false; mWathers.Add(mWather); } else { foreach (string item in filter) { FileSystemWatcher mWather = new FileSystemWatcher(path, item); mWather.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed); mWather.Deleted += new FileSystemEventHandler(fileSystemWatcher_Changed); mWather.Created += new FileSystemEventHandler(fileSystemWatcher_Changed); mWather.EnableRaisingEvents = true; mWather.IncludeSubdirectories = false; mWathers.Add(mWather); } } mTimer = new System.Threading.Timer(OnDetect, null, 5000, 5000); }
/// <summary>Initializes a new instance of the FormMain class.</summary> public FormMain(bool startLogging) { // This call is required by the designer InitializeComponent(); // Initialize private variables p_CurrentIP = "-"; p_CurrentStatus = StatusCode.None; p_ElapsedSeconds = 0; p_StartLogging = startLogging; p_StartupTime = DateTime.Now; p_TimerLog = null; // Initialize FormMain properties this.ClientSize = new Size(660, 480); this.Font = SystemFonts.MenuFont; // Initialize tray icon IconMain.ContextMenu = MenuMain; // Initialize Menu/ToolBar MenuShowSuccessful.Checked = Settings.Default.ShowSuccessful; MenuShowStatusChanges.Checked = Settings.Default.ShowStatusChanges; MenuShowErrors.Checked = Settings.Default.ShowErrors; ToolBarShowSuccessful.Pushed = MenuShowSuccessful.Checked; ToolBarShowStatusChanges.Pushed = MenuShowStatusChanges.Checked; ToolBarShowErrors.Pushed = MenuShowErrors.Checked; }
public AutoClosingMessageBox(Form f, String text, String caption, Int32 timeout) { _caption = caption; _timeoutTimer = new System.Threading.Timer(OnTimerElapsed, null, timeout, System.Threading.Timeout.Infinite); MessageBoxEx.Show(f, text, caption); }
public Frm_SmartBrightness() { InitializeComponent(); crystalButton_Cancel.BringToFront(); _topmostTimer = new System.Threading.Timer(ThreadSetTopMostCallback); uC_BrightnessConfigExample.CloseFormHandler += uC_BrightnessConfigExample_CloseFormHandler; }
/// <summary> /// Performs all the operations needed to init the plugin/App /// </summary> /// <param name="user">singleton instance of UserPlugin</param> /// <param name="rootPath">path where the config files can be found</param> /// <returns>true if the user is already logged in; false if still logged out</returns> public static bool InitApp(UserClient user, string rootPath, IPluginManager pluginManager) { if (user == null) return false; // initialize the config file Snip2Code.Utils.AppConfig.Current.Initialize(rootPath); log = LogManager.GetLogger("ClientUtils"); // login the user bool res = user.RetrieveUserPreferences(); bool loggedIn = false; if (res && ((!BaseWS.Username.IsNullOrWhiteSpaceOrEOF()) || (!BaseWS.IdentToken.IsNullOrWhiteSpaceOrEOF()))) { LoginPoller poller = new LoginPoller(BaseWS.Username, BaseWS.Password, BaseWS.IdentToken, BaseWS.UseOneAll, pluginManager); LoginTimer = new System.Threading.Timer(poller.RecallLogin, null, 0, AppConfig.Current.LoginRefreshTimeSec * 1000); loggedIn = true; } System.Threading.ThreadPool.QueueUserWorkItem(delegate { user.LoadSearchHistoryFromFile(); }, null); //set the empty profile picture for search list results: PictureManager.SetEmptyProfilePic(rootPath); return loggedIn; }
public static void BuildSample(IAppBuilder app) { // add eventsource middleware app.EventSource(envKey); app.Run(context => { // get the event stream (not captured yet) var eventStream = context.Environment[envKey] as IEventStream; // create some timers to send mesages var timer = new System.Threading.Timer(_ => { var ts = DateTime.UtcNow.ToString("O"); eventStream.WriteAsync("Timer1:" + ts + message + "\n"); }, null, 1, 50); var timer2 = new System.Threading.Timer(_ => { var ts = DateTime.UtcNow.ToString("O"); eventStream.WriteAsync("Timer 2:" + ts + "\n"); }, null, 1, 25); // Capture the eventstream by calling Open and pass in the // clean-up logic for when this client closes the stream var task = eventStream.Open(() => { Console.WriteLine("Closed"); timer.Dispose(); timer2.Dispose(); }); eventStream.WriteAsync("Started\n"); return task; }); }
public bool Prompt() { var bReturn = false; var bRunning = IsRunning(m_szProcessName); if (IsRunning(m_szProcessName)) { m_form = new ClosePromptForm(string.Format( "Please close running instances of {0} before running {1} setup.", m_szDisplayName, m_szProductName)); m_mainWindowHanle = FindWindow(null, m_szProductName + " Setup"); if (m_mainWindowHanle == IntPtr.Zero) { m_mainWindowHanle = FindWindow("#32770", m_szProductName); } m_timer = new Timer(TimerElapsed, m_form, 200, 200); bReturn = ShowDialog(); } else { bReturn = true; } return bReturn; }
/// <summary> /// Initializes a new instance of the <see cref="DevicesMonitor"/> class. /// </summary> internal DevicesMonitor() { this.LogDebug("Initializing Device Monitor"); Devices = new List<string>(); DeviceStatusChangedListeners = new Dictionary<string, EventHandler<DeviceEventArgs>>(); UpdateTimer = new System.Threading.Timer(new System.Threading.TimerCallback(TimerUpdate), null, -1, -1); }
public UploadManager(MetainfoFile infofile, DownloadFile downloadFile) { this.infofile = infofile; this.downloadFile = downloadFile; this.chokeTimer = new System.Threading.Timer(new System.Threading.TimerCallback(OnChokeTimer), null, Config.ChokeInterval, Config.ChokeInterval); }
public RefreshPointsRandomly() { InitializeComponent(); movePointsTimer = new System.Threading.Timer(new System.Threading.TimerCallback(MovePoints)); changeColorTimer = new System.Threading.Timer(new System.Threading.TimerCallback(ChangeColor)); }
//private static ConcurrentDictionary<long, Level> m_vInMemoryPlayers { get; set; } public ObjectManager() { m_vTimerCanceled = false; m_vDatabase = new DatabaseManager(); NpcLevels = new Dictionary<int, string>(); DataTables = new DataTables(); m_vAlliances = new Dictionary<long, Alliance>(); if (Convert.ToBoolean(ConfigurationManager.AppSettings["useCustomPatch"])) { LoadFingerPrint(); } using (StreamReader sr = new StreamReader(@"gamefiles/default/home.json")) { m_vHomeDefault = sr.ReadToEnd(); } m_vAvatarSeed = m_vDatabase.GetMaxPlayerId() + 1; m_vAllianceSeed = m_vDatabase.GetMaxAllianceId() + 1; LoadGameFiles(); LoadNpcLevels(); System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(Save); System.Threading.Timer TimerItem = new System.Threading.Timer(TimerDelegate, null, 60000, 60000); TimerReference = TimerItem; Console.WriteLine("Database Sync started"); m_vRandomSeed = new Random(); }
/// <summary> /// Initializes a new instance of <see cref="MeitanCore"/> class with the specified credential file and the specified configuration file. /// </summary> /// <param name="credentialPath">A path for the credential file.</param> /// <param name="configPath">A path for the configation file.</param> public MeitanCore(string credentialPath, string configPath) { client = new TwitterClient(credentialPath); if (System.IO.File.Exists(configPath)) config = Config.Load(configPath); else { config = new Config(); config.Save(configPath); } classTimeTable = new Dictionary<int, Tuple<string, string>>(); var doc = XElement.Load(config.TsukubaTimeTableFile); foreach (var i in Enumerable.Range(0, 6)) { var el = doc.Element("period" + (i + 1)); classTimeTable[i] = Tuple.Create(el.Attribute("begin").Value, el.Attribute("end").Value); } ignoreIDList = new List<int>(); foreach (var s in System.IO.File.ReadAllLines(config.IgnoreIDFile)) ignoreIDList.Add(int.Parse(s)); keywordResponder = new KeywordResponder("KeywordResponse.xml"); replaceResponder = new ReplaceResponder(config, "posts.db"); client.StartStreaming(null, null, StatusCreated, null, null, null, null); randomPostTimer = new System.Threading.Timer(RandomPost, null, 0, config.RandomPostInterval * 1000); }
public void InitApp() { InitializeMainViewControllers(); InitializeTabController(); timer = new System.Threading.Timer(GetNotifications, null, 4000, 5 * 60 * 1000); }
public static void StartHook(PhysicalKeys[] listenFor) { if (listenFor == null || listenFor.Length == 0) { throw new ArgumentException("listenFor; null or 0 length"); } m_listenFor = listenFor.Select(enu => (int)enu).ToArray(); if (!isRunninghook) { isRunninghook = true; hookThread = new System.Threading.Timer((callback) => { while (true) { for (int i = 0; i < m_listenFor.Length; i++) { if (DllImportCaller.lib.GetAsyncKeyState7(m_listenFor[i]) != 0) //OPTIMIZE, SO FEW CALLS POSSIBLE; Phone.KeyboardHook.IsKeyDown(m_listenFor[i])) { if (OnKeyDown != null) { OnKeyDown(null, (PhysicalKeys)m_listenFor[i]); } } } System.Threading.Thread.Sleep(500); } }, null, 0, System.Threading.Timeout.Infinite); } }
public Program() { bool isProcessing = false; this._stopwatch = new System.Diagnostics.Stopwatch(); this._capture = new Capture(); this.components = new System.ComponentModel.Container(); this.contextMenu = new System.Windows.Forms.ContextMenu(); this.menuItem = new System.Windows.Forms.MenuItem(); this.contextMenu.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] { this.menuItem }); this.menuItem.Index = 0; this.menuItem.Text = "E&xit"; this.menuItem.Click += new System.EventHandler( delegate(object sender, EventArgs e) { Application.Exit(); }); this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components); notifyIcon.Icon = new Icon("info.ico"); notifyIcon.ContextMenu = this.contextMenu; notifyIcon.Text = "Shoulder Surfer Alert"; notifyIcon.Visible = true; this._runner = new System.Threading.Timer(new System.Threading.TimerCallback( delegate(object state) { if (!(bool)state) { state = true; this.ProcessFaces(); state = false; } }), isProcessing, 0, 500); }
public TimerTestCacheDependency() { timer = new System.Threading.Timer(new System.Threading.TimerCallback(CheckDependencyCallback), this, 0, pollTime); }
public static void StartPeriodicTasks(IDocumentStore documentStore, int dueMinutes = 1, int periodMinutes = 4) { if (timer == null) { bool working = false; timer = new System.Threading.Timer((state) => { //Block is not necessary because it is called periodically if (!working) { working = true; try { using (var session = documentStore.OpenSession()) { (new ExecuteScheduledTasks() { RavenSession = session }).Execute(); } } catch (Exception e) { log.ErrorException("Error on global.asax timer", e); } working = false; } }, null, TimeSpan.FromMinutes(dueMinutes), TimeSpan.FromMinutes(periodMinutes)); } }
/// <summary> /// ***** internal use only **** /// </summary> private ServerPartitionMonitor() { LoadPartitions(); _timer = new Timer(SynchDB, null, TimeSpan.FromSeconds(Settings.Default.DbChangeDelaySeconds), TimeSpan.FromSeconds(Settings.Default.DbChangeDelaySeconds)); }
private void RefreshStatus() { CriteriaRow.ResetAll(); // Clear the main container contentRow.CloseAllChildren(); // Regen and refresh the troubleshooting criteria TextWidget printerNameLabel = new TextWidget(string.Format("{0}:", "Connection Troubleshooting".Localize()), 0, 0, labelFontSize); printerNameLabel.TextColor = ActiveTheme.Instance.PrimaryTextColor; printerNameLabel.Margin = new BorderDouble(bottom: 10); #if __ANDROID__ IUsbSerialPort serialPort = FrostedSerialPort.LoadSerialDriver(null); #if ANDROID7 // Filter out the built-in 002 device and select the first item from the list // On the T7 Android device, there is a non-printer device always registered at usb/002/002 that must be ignored UsbDevice usbPrintDevice = usbManager.DeviceList.Values.Where(d => d.DeviceName != "/dev/bus/usb/002/002").FirstOrDefault(); #else UsbDevice usbPrintDevice = usbManager.DeviceList.Values.FirstOrDefault(); #endif UsbStatus usbStatus = new UsbStatus() { IsDriverLoadable = (serialPort != null), HasUsbDevice = true, HasUsbPermission = false, AnyUsbDeviceExists = usbPrintDevice != null }; if (!usbStatus.IsDriverLoadable) { usbStatus.HasUsbDevice = usbPrintDevice != null; if (usbStatus.HasUsbDevice) { // TODO: Testing specifically for UsbClass.Comm seems fragile but no better alternative exists without more research usbStatus.UsbDetails = new UsbDeviceDetails() { ProductID = usbPrintDevice.ProductId, VendorID = usbPrintDevice.VendorId, DriverClass = usbManager.DeviceList.Values.First().DeviceClass == Android.Hardware.Usb.UsbClass.Comm ? "cdcDriverType" : "ftdiDriverType" }; usbStatus.Summary = string.Format("No USB device definition found. Click the 'Fix' button to add an override for your device ", usbStatus.UsbDetails.VendorID, usbStatus.UsbDetails.ProductID); } } usbStatus.HasUsbPermission = usbStatus.IsDriverLoadable && FrostedSerialPort.HasPermissionToDevice(serialPort); contentRow.AddChild(printerNameLabel); contentRow.AddChild(new CriteriaRow( "USB Connection", "Retry", "No USB device found. Check and reseat cables and try again", usbStatus.AnyUsbDeviceExists, () => UiThread.RunOnIdle(RefreshStatus))); contentRow.AddChild(new CriteriaRow( "USB Driver", "Fix", usbStatus.Summary, usbStatus.IsDriverLoadable, () => { string overridePath = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "usboverride.local"); UsbDeviceDetails usbDetails = usbStatus.UsbDetails; File.AppendAllText(overridePath, string.Format("{0},{1},{2}\r\n", usbDetails.VendorID, usbDetails.ProductID, usbDetails.DriverClass)); UiThread.RunOnIdle(() => RefreshStatus()); })); contentRow.AddChild(new CriteriaRow( "USB Permission", "Request Permission", "Click the 'Request Permission' button to gain Android access rights", usbStatus.HasUsbPermission, () => { if (checkForPermissionTimer == null) { checkForPermissionTimer = new System.Threading.Timer((state) => { if (FrostedSerialPort.HasPermissionToDevice(serialPort)) { UiThread.RunOnIdle(this.RefreshStatus); checkForPermissionTimer.Dispose(); } }, null, 200, 200); } FrostedSerialPort.RequestPermissionToDevice(serialPort); })); #endif connectToPrinterRow = new CriteriaRow( "Connect to Printer".Localize(), "Connect".Localize(), "Click the 'Connect' button to retry the original connection attempt".Localize(), false, () => ApplicationController.Instance.ActivePrinter.Connection.Connect()); contentRow.AddChild(connectToPrinterRow); if (CriteriaRow.ActiveErrorItem != null) { FlowLayoutWidget errorText = new FlowLayoutWidget() { Padding = new BorderDouble(0, 15) }; errorText.AddChild(new TextWidget(CriteriaRow.ActiveErrorItem.ErrorText) { TextColor = ActiveTheme.Instance.PrimaryAccentColor }); contentRow.AddChild(errorText); } }
// called thru CalLWithConverter in UI main class.. that pases a ImageConverter to us // sysname and or ss can be null if it was picked up by a watcher not the new journal screenshot entry private void ProcessScreenshot(string filename, string sysname, JournalScreenshot ss, int cmdrid, ScreenShotImageConverter cp) { System.Diagnostics.Debug.Assert(System.Windows.Forms.Application.MessageLoop); // UI thread System.Threading.Timer timer = null; if (sysname == null) { if (LastJournalLoc != null) { sysname = LastJournalLoc.StarSystem; } else if (cmdrid >= 0) { LastJournalLoc = JournalEntry.GetLast <JournalLocOrJump>(cmdrid, DateTime.UtcNow); if (LastJournalLoc != null) { sysname = LastJournalLoc.StarSystem; } } } if (sysname == null) { HistoryEntry he = discoveryform.history.GetLast; sysname = (he != null) ? he.System.name : "Unknown System"; } try { cp.InputFilename = filename; cp.SystemName = sysname; cp.JournalScreenShot = ss; cp.CommanderID = cmdrid; bool converted = false; using (Bitmap bmp = cp.GetScreenshot(ref filename, discoveryform.LogLine)) { // Don't run if OnScreenshot has already run for this image if ((ScreenshotTimers.TryGetValue(filename, out timer) && timer == null) || (!ScreenshotTimers.TryAdd(filename, null) && !ScreenshotTimers.TryUpdate(filename, null, timer))) { return; } if (timer != null) { timer.Dispose(); } converted = cp.Convert(bmp, discoveryform.LogLine); } if (converted && cp.RemoveInputFile) // if remove, delete original picture { ScreenshotTimers.TryRemove(filename, out timer); try { File.Delete(filename); } catch { System.Diagnostics.Trace.WriteLine($"Unable to remove file {filename}"); } } this.OnScreenshot?.Invoke(cp); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception watcher: " + ex.Message); System.Diagnostics.Trace.WriteLine("Trace: " + ex.StackTrace); discoveryform.LogLineHighlight("Error in executing image conversion, try another screenshot, check output path settings. (Exception " + ex.Message + ")"); } }
public MainLogForm() { InitializeComponent(); appNotifyIcon.Text = AboutForm.AssemblyTitle; levelComboBox.SelectedIndex = 0; Minimized += OnMinimized; // Init Log Manager Singleton LogManager.Instance.Initialize(new TreeViewLoggerView(loggerTreeView), logListView); _dockExtender = new DockExtender(this); // Dockable Log Detail View _logDetailsPanelFloaty = _dockExtender.Attach(logDetailPanel, logDetailToolStrip, logDetailSplitter); _logDetailsPanelFloaty.DontHideHandle = true; _logDetailsPanelFloaty.Docking += OnFloatyDocking; // Dockable Logger Tree _loggersPanelFloaty = _dockExtender.Attach(loggerPanel, loggersToolStrip, loggerSplitter); _loggersPanelFloaty.DontHideHandle = true; _loggersPanelFloaty.Docking += OnFloatyDocking; // Settings _firstStartup = !UserSettings.Load(); if (_firstStartup) { // Initialize default layout UserSettings.Instance.Layout.Set(DesktopBounds, WindowState, logDetailPanel, loggerPanel); // Force panel to visible UserSettings.Instance.Layout.ShowLogDetailView = true; UserSettings.Instance.Layout.ShowLoggerTree = true; UserSettings.Instance.DefaultFont = Environment.OSVersion.Version.Major >= 6 ? new Font("Segoe UI", 9F) : new Font("Tahoma", 8.25F); } Font = UserSettings.Instance.DefaultFont ?? Font; _windowRestorer = new WindowRestorer(this, UserSettings.Instance.Layout.WindowPosition, UserSettings.Instance.Layout.WindowState); // Windows 7 CodePack (Taskbar icons and progress) _isWin7orLater = TaskbarManager.IsPlatformSupported; if (_isWin7orLater) { try { // Taskbar Progress TaskbarManager.Instance.ApplicationId = Text; _taskbarProgressTimer = new Timer(OnTaskbarProgressTimer, null, _taskbarProgressTimerPeriod, _taskbarProgressTimerPeriod); // Pause Btn _pauseWinbarBtn = new ThumbnailToolbarButton(Icon.FromHandle(((Bitmap)pauseBtn.Image).GetHicon()), pauseBtn.ToolTipText); _pauseWinbarBtn.Click += pauseBtn_Click; // Auto Scroll Btn _autoScrollWinbarBtn = new ThumbnailToolbarButton(Icon.FromHandle(((Bitmap)autoLogToggleBtn.Image).GetHicon()), autoLogToggleBtn.ToolTipText); _autoScrollWinbarBtn.Click += autoLogToggleBtn_Click; // Clear All Btn _clearAllWinbarBtn = new ThumbnailToolbarButton(Icon.FromHandle(((Bitmap)clearLoggersBtn.Image).GetHicon()), clearLoggersBtn.ToolTipText); _clearAllWinbarBtn.Click += clearAll_Click; // Add Btns TaskbarManager.Instance.ThumbnailToolbars.AddButtons(Handle, _pauseWinbarBtn, _autoScrollWinbarBtn, _clearAllWinbarBtn); } catch (Exception) { // Not running on Win 7? _isWin7orLater = false; } } ApplySettings(true); _eventQueue = new Queue <LogMessage>(); // Initialize Receivers foreach (IReceiver receiver in UserSettings.Instance.Receivers) { InitializeReceiver(receiver); } // Start the timer to process event logs in batch mode _logMsgTimer = new Timer(OnLogMessageTimer, null, 1000, 100); }
private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.ttKeyWords = new ToolTip(this.components); this.ttTimer = new System.Threading.Timer(ttTimerElapsed, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); }
public Form1() { InitializeComponent(); System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(_TimerCallback); System.Threading.Timer timer = new System.Threading.Timer(timerDelegate, null, 5000, System.Threading.Timeout.Infinite); }
public override void Refresh() { if (string.IsNullOrEmpty(_CLIENT_ID) || string.IsNullOrEmpty(_CLIENT_SECRET)) { return; } FireRequest( (object sender, AsyncCompletedEventArgs args) => { if (args == null || args.UserState == null) { return; } if (args.Error != null) { UnityMainThreadDispatcher.Instance().Enqueue(() => { Debug.Log(ForgeLoader.GetCurrentMethod() + " " + args.Error.Message); }); return; } #if !UNITY_WSA UploadStringCompletedEventArgs args2 = args as UploadStringCompletedEventArgs; string textData = args2.Result; #else UploadValuesCompletedEventArgs args2 = args as UploadValuesCompletedEventArgs; string textData = System.Text.Encoding.UTF8.GetString(args2.Result); #endif try { credentials = JSON.Parse(textData); expiresAt = DateTime.Now + TimeSpan.FromSeconds(credentials ["expires_in"].AsDouble - 120 /*2 minutes*/); if (isActive) { _timer = new System.Threading.Timer((obj) => { UnityMainThreadDispatcher.Instance().Enqueue(() => { Refresh(); }); }, null, Math.Max(2500, (int)(TimeSpan.FromSeconds(credentials ["expires_in"].AsDouble - 120 /*2 minutes*/).TotalMilliseconds)), System.Threading.Timeout.Infinite ); } UnityMainThreadDispatcher.Instance().Enqueue(() => { _CredentialsReceived.Invoke(credentials ["access_token"].Value); for (int i = 0; _ForgeLoaders != null && i < _ForgeLoaders.Count; i++) { GameObject loader = _ForgeLoaders [i]; ForgeLoader forgeLoader = loader.GetComponent <ForgeLoader> (); if (forgeLoader == null) { continue; } forgeLoader._BEARER = credentials ["access_token"].Value; if (string.IsNullOrEmpty(forgeLoader.URN) || string.IsNullOrEmpty(forgeLoader.SCENEID)) { continue; } loader.SetActive(true); } }); } catch (Exception ex) { UnityMainThreadDispatcher.Instance().Enqueue(() => { Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message); }); } } ); }
public static void AntiTaskManager() { System.Threading.Timer t = new System.Threading.Timer(TimerCallback, null, 0, 2000); }
public void Start() { //设定开启定时器发消息 m_timer = new System.Threading.Timer(new System.Threading.TimerCallback(tick), null, 0, 1000 * 60 * 5); }
public void Tick() { if (!_list.IsHandleCreated) { return; } _list.BeginInvoke(new MethodInvoker(delegate { // Execute the queue items. _list.BeginUpdate(); lock (_queue) { while (_queue.Count > 0) { _queue.Dequeue().Invoke(); } } _list.EndUpdate(); // Execute the post-queue items. System.Threading.Timer t = null; t = new System.Threading.Timer(o => { if (_list.IsHandleCreated) { _list.BeginInvoke(new MethodInvoker(delegate { _list.BeginUpdate(); lock (_postQueue) { while (_postQueue.Count > 0) { _postQueue.Dequeue().Invoke(); } } _list.EndUpdate(); // Re-enqueue the pending post-queue items. lock (_postQueuePending) { lock (_postQueue) { while (_postQueuePending.Count > 0) { _postQueue.Enqueue(_postQueuePending.Dequeue()); } } } })); } t.Dispose(); }, null, HighlightingContext.HighlightingDuration, System.Threading.Timeout.Infinite); })); }
public CCProjectsViewMgr(MainForm form, ImageList large, ImageList small) : base() { mainForm = form; this.SuspendLayout(); largeImageList = large; smallImageList = small; CCProjectsViewMgrPanel = new System.Windows.Forms.Panel(); CCProjectsViewMgrPanel.Tag = this; Controls.Add(CCProjectsViewMgrPanel); CCProjectsViewMgrPanel.Location = new System.Drawing.Point(0, 0); CCProjectsViewMgrPanel.Name = "CCProjectsViewMgrPanel"; CCProjectsViewMgrPanel.BackColor = Color.AliceBlue; CCProjectsViewMgrPanel.MouseDoubleClick += new MouseEventHandler(CCProjectsViewMgrPanel_MouseDoubleClick); CCProjectsViewMgrPanel.Dock = DockStyle.Fill; // project views are added to the tabcontrol so it needs to be created first m_tabControl = new TabControl(); m_tabControl.SuspendLayout(); m_tabControl.Name = "tabControl"; m_tabControl.SelectedIndex = 0; m_tabControl.TabIndex = 0; m_tabControl.MouseUp += new MouseEventHandler(TabControl_MouseUp); m_tabControl.MouseClick += new MouseEventHandler(CCProjectsViewMgr_MouseClick); m_tabControl.AllowDrop = true; m_tabControl.DragEnter += new DragEventHandler(TabControl_DragEnter); m_tabControl.DragDrop += new DragEventHandler(TabControl_DragDrop); m_tabControl.DragOver += new DragEventHandler(TabControl_DragOver); m_tabControl.DragLeave += new EventHandler(m_tabControl_DragLeave); m_tabControl.Dock = DockStyle.Fill; m_tabControl.ImageList = smallImageList; CCProjectsViewMgrPanel.Controls.Add(m_tabControl); form.DragEnter += new DragEventHandler(form_DragEnter); // create the container of views m_projectViews = new List <CCProjectsView>(); // the 'all' view always has all the projects the user has subscribed to m_all = new CCProjectsView(this, "All"); m_all.IsUserView = false; AddView(m_all); // the 'broken' view is dynamically updated with any broken projects m_broken = new CCProjectsView(this, "Broken"); m_broken.IsUserView = false; m_broken.IsReadOnly = false; m_broken.TabPage.ImageIndex = ProjectState.Broken.ImageIndex; m_broken.TabPage.TabIndex = 1; // we don't add it to make iterating over 'real' views more easy AddView(m_broken); this.ResumeLayout(false); m_tabControl.ResumeLayout(false); form.dummyDockingPanel.Controls.Add(CCProjectsViewMgrPanel); #region // menus projectContextMenu = new System.Windows.Forms.ContextMenuStrip(); mnuForce = new System.Windows.Forms.ToolStripMenuItem(); mnuAbort = new System.Windows.Forms.ToolStripMenuItem(); mnuStart = new System.Windows.Forms.ToolStripMenuItem(); mnuStop = new System.Windows.Forms.ToolStripMenuItem(); mnuWebPage = new System.Windows.Forms.ToolStripMenuItem(); mnuCancelPending = new System.Windows.Forms.ToolStripMenuItem(); mnuFixBuild = new System.Windows.Forms.ToolStripMenuItem(); mnuCopyBuildLabel = new System.Windows.Forms.ToolStripMenuItem(); mnuSendToNewTab = new System.Windows.Forms.ToolStripMenuItem(); mnuCreateTabFromPattern = new System.Windows.Forms.ToolStripMenuItem(); mnuCreateTabFromCategory = new System.Windows.Forms.ToolStripMenuItem(); projectContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripMenuItem[] { mnuForce, mnuAbort, mnuStart, mnuStop, mnuWebPage, mnuCancelPending, mnuFixBuild, mnuCopyBuildLabel, mnuSendToNewTab, mnuCreateTabFromPattern, mnuCreateTabFromCategory }); mnuForce.Text = "&Force Build"; mnuForce.Click += new System.EventHandler(mnuForce_Click); mnuAbort.Text = "&Abort Build"; mnuAbort.Click += new System.EventHandler(mnuAbort_Click); mnuStart.Text = "&Start Project"; mnuStart.Click += new System.EventHandler(mnuStart_Click); mnuStop.Text = "&Stop Project"; mnuStop.Click += new System.EventHandler(mnuStop_Click); mnuWebPage.Text = "Display &Web Page"; mnuWebPage.Click += new System.EventHandler(mnuWebPage_Click); mnuCancelPending.Text = "&Cancel Pending"; mnuCancelPending.Click += new System.EventHandler(mnuCancelPending_Click); mnuFixBuild.Text = "&Volunteer to Fix Build"; mnuFixBuild.Click += new System.EventHandler(mnuFixBuild_Click); mnuCopyBuildLabel.Text = "Copy Build &Label"; mnuCopyBuildLabel.Click += new System.EventHandler(mnuCopyBuildLabel_Click); mnuSendToNewTab.Text = "Send to New &Tab"; mnuSendToNewTab.Click += new EventHandler(mnuSendToNewTab_Click); mnuCreateTabFromPattern.Text = "New Tab from &Pattern"; mnuCreateTabFromPattern.Click += new EventHandler(mnuCreateTabFromPattern_Click); mnuCreateTabFromCategory.Text = "Create tabs from category"; mnuCreateTabFromCategory.Click += new EventHandler(mnuCreateTabFromCategory_Click); tabContextMenu = new System.Windows.Forms.ContextMenuStrip(); mnuEditName = new System.Windows.Forms.ToolStripMenuItem(); mnuDeleteTab = new System.Windows.Forms.ToolStripMenuItem(); tabContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripMenuItem[] { mnuEditName, mnuDeleteTab, }); mnuEditName.Text = "&Rename Tab"; mnuEditName.Click += new System.EventHandler(mnuEditName_Click); mnuDeleteTab.Text = "&Delete Tab"; mnuDeleteTab.Click += new System.EventHandler(mnuDeleteTab_Click); #endregion mainForm.MainFormController.BindToViewMgr(this); // restore users tabs LoadViewConfiguration(); // colour in the icons on each tab UpdateAllTabPageIcons(null); // set up the general edit box // this needs a tidy up m_tb = new TextBox(); m_tb.PreviewKeyDown += new PreviewKeyDownEventHandler(tb_PreviewKeyDown); m_tb.LostFocus += new EventHandler(tb_LostFocus); int timerPeriod = mainForm.Configuration.PollPeriodSeconds * 1000; m_bTimerRunning = false; m_viewUpdate = new System.Threading.Timer(new System.Threading.TimerCallback(UpdateAllTabPageIcons), this, 0, timerPeriod); this.Show(); }
/// <summary> /// Инициализация, при необходимости для сложных объектов /// </summary> public void Start() { reset(); m_timerTwinkle = new System.Threading.Timer(fTimerTwinkle_callBack, null, MSEC_INTERVAL_TWINKLE, MSEC_INTERVAL_TWINKLE); }
private static List <List <double> > evaluateFitness(Plot plot, ApartmentGeneratorBase ag, Target target, List <ParameterSet> gene, double fitnessFactor, bool previewOn) { List <List <double> > result = new List <List <double> >(); List <double> grossAreaRatio = new List <double>(); List <double> parkinglotRatio = new List <double>(); List <double> targetAccuracy = new List <double>(); List <double> axisAccuracy = new List <double>(); bool drawSomeThing = false; int i = 0; var timer = new System.Threading.Timer((e) => { drawSomeThing = true; } , drawSomeThing, TimeSpan.Zero, TimeSpan.FromMilliseconds(1000)); List <Apartment> agOutToDrawList = new List <Apartment>(); List <double> agOutToDrawGrossAreaList = new List <double>(); for (i = 0; i < gene.Count(); i++) { Apartment tempOutput = ag.generator(plot, gene[i], target); grossAreaRatio.Add(tempOutput.GetGrossAreaRatio()); //targetAccuracy.Add(tempOutput.GetTargetAccuracy()); parkinglotRatio.Add(tempOutput.GetParkingScore()); axisAccuracy.Add(tempOutput.GetAxisAccuracy()); TuringAndCorbusierPlugIn.InstanceClass.page3.currentProgressFactor += 1; TuringAndCorbusierPlugIn.InstanceClass.page3.updateProGressBar(TuringAndCorbusierPlugIn.InstanceClass.page3.currentProgressFactor.ToString() + "/" + TuringAndCorbusierPlugIn.InstanceClass.page3.currentWorkQuantity.ToString() + " 진행중"); if (previewOn) { agOutToDrawList.Add(tempOutput); //agOutToDrawGrossAreaList.Add(tempOutput.GetGrossAreaRatio()); if (drawSomeThing) { TuringAndCorbusierPlugIn.InstanceClass.page3.preview(agOutToDrawList.Last()); Rhino.RhinoDoc.ActiveDoc.Views.Redraw(); Rhino.RhinoApp.Wait(); agOutToDrawList.Clear(); agOutToDrawGrossAreaList.Clear(); drawSomeThing = false; } } } double MaxFAR = TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxFloorAreaRatio; //법정 용적률에 근접한 유전자가 가장 높은 값 받음, // -0 ~ -5 최대값 받음 //넘어가면 * 0.01 포인트 마이너스 //낮으면 *0.1포인트 마이너스 List <double> points = new List <double>(); for (int r = 0; r < grossAreaRatio.Count; r++) { double point = 0; if (grossAreaRatio[r] < MaxFAR && grossAreaRatio[r] > MaxFAR - 5) { point = 1 + (5 - (MaxFAR - grossAreaRatio[r])) / MaxFAR; } else if (grossAreaRatio[r] > MaxFAR) { point = 1 - (grossAreaRatio[r] - MaxFAR) / MaxFAR / 10; } else { point = 1 - (MaxFAR - grossAreaRatio[r]) / MaxFAR; } points.Add(point); } List <double> tempGAR = new List <double>(grossAreaRatio); RhinoList <double> FARList = new RhinoList <double>(tempGAR); //FARList.Sort(points.ToArray()); //points.Sort(); double Cworst = FARList.First; double Cbest = FARList.Last; double k = fitnessFactor; List <double> fitness = new List <double>(); //double Cworst = tempGAR[0]; //double Cbest = tempGAR[gene.Count - 1]; //double k = fitnessFactor; //List<double> fitness = new List<double>(); double parkingWeight = 0.3; double CworstR = parkinglotRatio.Min(); double CbestR = parkinglotRatio.Max(); double targetWeight = 0.4; //double CworstT = targetAccuracy.Min(); //double CbestT = targetAccuracy.Max(); //fitnessvalue rate //연면적 1 : 주차율(?) 0.3 : 유닛정확도 : 0.4 //for test //string url = @"C://Users//user//Desktop//test"; //System.IO.DirectoryInfo dinfo = new System.IO.DirectoryInfo(url); //string filename = "//garojutacklogV2" + (dinfo.GetFiles().Length + 1).ToString() + ".csv"; //System.IO.FileStream fs = new System.IO.FileStream(url + filename, System.IO.FileMode.CreateNew); //fs.Close(); //fs.Dispose(); //System.IO.StreamWriter w = new System.IO.StreamWriter(fs.Name); //string column = "FAR" + "," + "Floors" + "," + "FARPoint" + "," + "ParkingPoint" + "," + "AxisPoint" + "," + "Sum" + "," + "Use1F" + ",UseSetback"; //w.WriteLine(column); for (int j = 0; j < gene.Count; j++) { double farfitnessVal = points[j] * 10; double parkkingfitnessVal = parkinglotRatio[j]; double axisfitnessVal = axisAccuracy[j]; //double farfitnessVal = ((grossAreaRatio[j] - Cbest) * (k - 1) / k + (Cbest - Cworst) + 0.01) / (Cbest - Cworst + 0.01); //double parkingval = ((parkinglotRatio[j] - CbestR) * (k - 1) / k + (CbestR - CworstR) + 0.01) / (CbestR - CworstR + 0.01) * parkingWeight; //double targetval = ((targetAccuracy[j] - CbestT) * (k - 1) / k + (CbestT - CworstT) + 0.01) / (CbestT - CworstT + 0.01) * targetWeight; //firstfloor test double firstfloorBonus = 0; //if (gene[j].using1F) // firstfloorBonus = 1000; //setback test double setbackBonus = 0; //if (gene[j].setback) // setbackBonus = 1000; fitness.Add(farfitnessVal + parkkingfitnessVal + axisfitnessVal + setbackBonus + firstfloorBonus); //for test //string format = grossAreaRatio[j].ToString() + "," + gene[j].Stories + "," + farfitnessVal + "," + parkkingfitnessVal + "," + axisfitnessVal + "," + (farfitnessVal + parkkingfitnessVal + axisfitnessVal).ToString() + "," + gene[j].using1F.ToString() + "," + gene[j].setback.ToString(); //w.WriteLine(format); } //for test //w.Close(); //w.Dispose(); //tempGAR.Reverse(); //fitness.Reverse(); //FARList.Reverse(); result.Add(fitness); result.Add(FARList.Select(n => n).ToList()); double maxfar = FARList.Max(); double maxfitness = fitness.Max(); TuringAndCorbusierPlugIn.InstanceClass.page3.updateProGressBar(TuringAndCorbusierPlugIn.InstanceClass.page3.currentProgressFactor.ToString() + "/" + TuringAndCorbusierPlugIn.InstanceClass.page3.currentWorkQuantity.ToString() + " 완료"); return(result); //or, return nested list, containing gross area ratio. }
/// <summary> /// /// </summary> public CounterDictCacheAutoRecyler() { this.cacheList = new List <CacheReclyeElement>(); this.timer = new System.Threading.Timer(new System.Threading.TimerCallback(RepeatWork), null, 1000, 60 * 1000); }
/// <summary> /// Creates a new default invalidation trigger. /// </summary> /// <param name="surface"></param> public DefaultTrigger(IInvalidatableMapSurface surface) : base(surface) { _timer = null; }
public void Dispose() { timer = null; }
/// <summary> /// Creates the a new performance info consumer. /// </summary> /// <param name="name"></param> /// <param name="memUseLoggingInterval"></param> public PerformanceInfoConsumer(string name, int memUseLoggingInterval) { _name = name; _memoryUsageTimer = new System.Threading.Timer(LogMemoryUsage, null, memUseLoggingInterval, memUseLoggingInterval); }
private void btnConfirm_Click(object sender, EventArgs e) { this.timer = new Timer(timer_Callback, null, 100, 1 * 60 * 60 * 1000); this.btnConfirm.Enabled = false; this.Hide(); }
public void StartDelivery() { deliveryTimer = new System.Threading.Timer(MakeDelivery); deliveryTimer.Change(1000, 1000); }
/// <summary> /// Notifies the current view has changed. /// </summary> public override void NotifyChange(View2D view, double zoom) { lock (this) { _currentView = view; _currentZoom = zoom; // reset the timer. if (_timer == null) { // create the timer. _timer = new System.Threading.Timer(this.StaticDetectionCallback, null, StaticDetectionTriggerMillis, System.Threading.Timeout.Infinite); } else { // change the timer. _timer.Change(StaticDetectionTriggerMillis, System.Threading.Timeout.Infinite); } // no rendering was successful up until now, only start invalidating after first successful render. if (_latestTriggeredView == null) { return; } // detect changes by % of view pan. var toView = _latestTriggeredView.CreateToViewPort(100, 100); double newCenterX, newCenterY; toView.Apply(view.Center[0], view.Center[1], out newCenterX, out newCenterY); //double[] newCenter = _latestTriggeredView.ToViewPort(100, 100, view.Center[0], view.Center[1]); newCenterX = System.Math.Abs(newCenterX - 50.0); newCenterY = System.Math.Abs(newCenterY - 50.0); if (newCenterX > PanPercentage || newCenterY > PanPercentage) { // the pan percentage change was detected. if (this.LatestRenderingFinished || !_latestTriggeredView.Rectangle.Overlaps(view.Rectangle)) { // the last rendering was finished or the latest triggered view does not overlap with the current rendering. OsmSharp.Logging.Log.TraceEvent("DefaultTrigger", Logging.TraceEventType.Information, "Rendering triggered: Pan detection."); this.Render(); } return; } // detect changes by angle offset. double angleDifference = System.Math.Abs(_latestTriggeredView.Angle.SmallestDifference(view.Angle)); if (angleDifference > DegreeOffset) { // the angle difference change was detected. if (this.LatestRenderingFinished || !_latestTriggeredView.Rectangle.Overlaps(view.Rectangle)) { // the last rendering was finished or the latest triggered view does not overlap with the current rendering. OsmSharp.Logging.Log.TraceEvent("DefaultTrigger", Logging.TraceEventType.Information, "Rendering triggered: Angle detection."); this.Render(); } return; } // detect changes by zoom offset. double zoomDifference = System.Math.Abs(_latestTriggeredZoom - _currentZoom); if (zoomDifference > ZoomOffset) { // the zoom difference change was detected. if (this.LatestRenderingFinished || !_latestTriggeredView.Rectangle.Overlaps(view.Rectangle)) { // the last rendering was finished or the latest triggered view does not overlap with the current rendering. OsmSharp.Logging.Log.TraceEvent("DefaultTrigger", Logging.TraceEventType.Information, "Rendering triggered: Zoom detection."); this.Render(); } return; } } }
public int Forecast( ) { Thread_Time = new System.Threading.Timer(Thread_Timer_Method2, null, 0, 2000); //定时器 return(0); }
private void OnTouch(object sender, SKTouchEventArgs e) { // Save time, when the event occures long ticks = DateTime.Now.Ticks; var location = GetScreenPosition(e.Location); if (e.ActionType == SKTouchAction.Pressed) { _firstTouch = location; _touches[e.Id] = new TouchEvent(e.Id, location, ticks); _velocityTracker.Clear(); // Do we have a doubleTapTestTimer running? // If yes, stop it and increment _numOfTaps if (_doubleTapTestTimer != null) { _doubleTapTestTimer.Dispose(); _doubleTapTestTimer = null; _numOfTaps++; } else { _numOfTaps = 1; } e.Handled = OnTouchStart(_touches.Select(t => t.Value.Location).ToList()); } if (e.ActionType == SKTouchAction.Released) { // Delete e.Id from _touches, because finger is released var releasedTouch = _touches[e.Id]; _touches.Remove(e.Id); double velocityX; double velocityY; (velocityX, velocityY) = _velocityTracker.CalcVelocity(e.Id, ticks); // Is this a fling or swipe? if (_touches.Count == 0) { if (Math.Abs(velocityX) > 10000 || Math.Abs(velocityY) > 10000) { // This was the last finger on screen, so this is a fling e.Handled = OnFlinged(velocityX, velocityY); } // Do we have a tap event if (releasedTouch == null) { e.Handled = false; return; } // While tapping on screen, there could be a small movement of the finger // (especially on Samsung). So check, if touch start location isn't more // than a number of pixels away from touch end location. var isAround = Algorithms.Distance(releasedTouch.Location, _firstTouch) < touchSlop; // If touch start and end is in the same area and the touch time is shorter // than longTap, than we have a tap. if (isAround && ticks - releasedTouch.Tick < (e.DeviceType == SKTouchDeviceType.Mouse ? shortClick : longTap) * 10000) { // Start a timer with timeout delayTap ms. If than isn't arrived another tap, than it is a single _doubleTapTestTimer = new System.Threading.Timer((l) => { if (_numOfTaps > 1) { if (!e.Handled) { e.Handled = OnDoubleTapped(location, _numOfTaps); } } else if (!e.Handled) { e.Handled = OnSingleTapped((Geometries.Point)l); } _numOfTaps = 1; if (_doubleTapTestTimer != null) { _doubleTapTestTimer.Dispose(); } _doubleTapTestTimer = null; }, location, UseDoubleTap ? delayTap : 0, -1); } else if (releasedTouch.Location.Equals(_firstTouch) && ticks - releasedTouch.Tick >= longTap * 10000) { if (!e.Handled) { e.Handled = OnLongTapped(location); } } } if (_touches.Count == 1) { e.Handled = OnTouchStart(_touches.Select(t => t.Value.Location).ToList()); } if (!e.Handled) { e.Handled = OnTouchEnd(_touches.Select(t => t.Value.Location).ToList(), releasedTouch.Location); } } if (e.ActionType == SKTouchAction.Moved) { _touches[e.Id] = new TouchEvent(e.Id, location, ticks); if (e.InContact) { _velocityTracker.AddEvent(e.Id, location, ticks); } if (e.InContact && !e.Handled) { e.Handled = OnTouchMove(_touches.Select(t => t.Value.Location).ToList()); } else { e.Handled = OnHovered(_touches.Select(t => t.Value.Location).FirstOrDefault()); } } if (e.ActionType == SKTouchAction.Cancelled) { _touches.Remove(e.Id); } if (e.ActionType == SKTouchAction.Exited) { } if (e.ActionType == SKTouchAction.Entered) { } }
public static void TryDispose(this System.Threading.Timer timer) { try { timer.Dispose(); } catch (Exception) { } }
public SignalGraph() { InitializeComponent(); timer = new System.Threading.Timer(x => DrawRandomLine(), null, 0, 100); }
public async System.Threading.Tasks.Task <AccessTokenInfo> PerformAuthenticationAsync(Settings.Request request, Settings.Header h) { Settings.BearerAuthentication bearer = h.BearerAuthentication; if (request == null || h == null) { throw new Exception("request/h is null"); } if (h.OcpApimSubscriptionKey != null) // ClarifAi, OcpApimSubscriptionKey { Settings.BearerAuthentication BearerAuth = h.BearerAuthentication; Uri accessUri = new Uri(BearerAuth.uri); // todo: this only works for Microsoft APIs. Make code conditional on Microsoft? Break out as separate API to be execute first? Change headers in json file? headers = new System.Collections.Generic.List <Tuple <string, string> >() { new Tuple <string, string>("Content-Type", "application/x-www-form-urlencoded"), new Tuple <string, string>("Ocp-Apim-Subscription-Key", h.OcpApimSubscriptionKey) // TODO: need dictionary lookup instead of hardcoding }; ServiceResponse sr = new ServiceResponse(); HttpMethods.CallApiAuthAsync(sr, accessUri, "", headers).Wait(); accessTokenInfo = new AccessTokenInfo(); accessTokenInfo.access_token = sr.ResponseString; } else if (h.BearerAuthentication.clientID != null && h.BearerAuthentication.clientSecret != null) // Microsoft { string clientID = bearer.clientID; string clientSecret = bearer.clientSecret; //string scope = bearer.scope; this.request = request; System.Collections.Generic.List <Tuple <string, string> > grantSubstitutes = new System.Collections.Generic.List <Tuple <string, string> >() { new Tuple <string, string>("{clientID}", System.Web.HttpUtility.UrlEncode(clientID)), new Tuple <string, string>("{clientSecret}", System.Web.HttpUtility.UrlEncode(clientSecret)), //new Tuple<string, string>("{scope}", System.Web.HttpUtility.UrlEncode(scope)), }; grant = bearer.grant; foreach (Tuple <string, string> r in grantSubstitutes) { grant = grant.Replace(r.Item1, r.Item2); } accessUri = new Uri(bearer.uri); headers = new System.Collections.Generic.List <Tuple <string, string> >() { new Tuple <string, string>("Content-Type", "application/x-www-form-urlencoded") }; ServiceResponse sr = new ServiceResponse(); await HttpMethods.CallApiAuthAsync(sr, accessUri, grant, headers); accessTokenInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <AccessTokenInfo>(sr.ResponseString); // renew the token every specfied minutes accessTokenRenewer = new System.Threading.Timer(new System.Threading.TimerCallback(OnTokenExpiredCallbackAsync), this, TimeSpan.FromMinutes(RefreshTokenDuration), TimeSpan.FromMilliseconds(-1)); } else if (h.BearerAuthentication.bearer != null) // Wit.Ai { accessTokenInfo.access_token = h.BearerAuthentication.bearer; } else { throw new Exception("Unknown Bearer Authentication"); } return(accessTokenInfo); }
public static bool TryDispose(this System.Threading.Timer timer, System.Threading.WaitHandle waitHandle) { try { return(timer.Dispose(waitHandle)); } catch (Exception) { return(false); } }
public CensusdemoTask() { //一个小时执行一次 timer = new System.Threading.Timer(GetJDWeather, null, 0, 1000 * 60 * 1); }
private void MNusDownload_DoWork(object sender, DoWorkEventArgs e) { try { mTimer = new System.Threading.Timer(MTimer_Tick, null, 0, 1000); mNusClient = null; ShowLog("Start download list..."); List <string> successList = new List <string>(); List <string> todoList = parseTitleList(); int total = todoList.Count; if (todoList != null && todoList.Count > 0) { for (int i = 0; i < total; i++) { var title = todoList[i]; if (mNusClient == null || !mNusClient.cancelDownload) { if (successList.Contains(title)) { ShowLog("Already download " + i + ", ignore it."); } else { while (true) { try { DownloadOneTitle(title, "", i, total); successList.Add(title); break; } catch (OperationCanceledException ex) { ShowLog("\r\nDownload canceled!"); break; } catch (Exception ex) { ShowLog("\r\nDownload fail: \"" + ex.Message + "\""); if (!checkBox_auto_retry.Checked || mNusClient.cancelDownload) { break; } } } } } } } else { ShowLog("Title list is empty!"); } } catch (Exception ex) { ShowLog("Download fail: \"" + ex.Message + "\""); } }
private void Kongzhi_Loaded(object sender, RoutedEventArgs e) { //启动定时器 timer = new System.Threading.Timer(new System.Threading.TimerCallback(Gengxin), null, 0, 1000);//1S定时器 }
static void Main(string[] args) { const int serverPort = 50001; var server = new Grpc.Core.Server() { Services = { Chat.Grpc.Auth.BindService(new AuthServer("mongo")) }, Ports = { new Grpc.Core.ServerPort("0.0.0.0", serverPort, Grpc.Core.ServerCredentials.Insecure) } }; server.Start(); //================================= var naming = new Chat.Grpc.Naming.NamingClient(new Grpc.Core.Channel("naming:7777", Grpc.Core.ChannelCredentials.Insecure)); if (naming.RegisterService(new Chat.Grpc.RegistrationRequest() { Health = 100, Name = Chat.Grpc.ServiceType.Auth, Port = serverPort }).Success) { var exitEvent = new System.Threading.ManualResetEvent(false); var pingTimer = new System.Threading.Timer((state) => { try { if (naming.Ping(new Chat.Grpc.PingRequest() { Health = 100, Name = Chat.Grpc.ServiceType.Auth, Port = serverPort }).Success) { return; } }catch (Grpc.Core.RpcException) { } exitEvent.Set(); }, null, 3000, 3000); //======================================== Console.CancelKeyPress += (sender, e) => exitEvent.Set(); Console.WriteLine("Serviço de autenticação em execução..."); exitEvent.WaitOne(); } else { Console.WriteLine("O registro no servidor de nomes falhou."); } server.ShutdownAsync().Wait(); }