// Save the workflow instance state at the point of persistence with option of locking the instance state if it is shared // across multiple runtimes or multiple phase instance updates protected override void SaveWorkflowInstanceState(Activity rootActivity, bool unlock) { // Save the workflow Guid contextGuid = (Guid)rootActivity.GetValue(Activity.ActivityContextGuidProperty); Console.WriteLine("Saving instance: {0}\n", contextGuid); SerializeToFile( WorkflowPersistenceService.GetDefaultSerializedForm(rootActivity), contextGuid); // See when the next timer (Delay activity) for this workflow will expire TimerEventSubscriptionCollection timers = (TimerEventSubscriptionCollection)rootActivity.GetValue(TimerEventSubscriptionCollection.TimerCollectionProperty); TimerEventSubscription subscription = timers.Peek(); if (subscription != null) { // Set a system timer to automatically reload this workflow when its next timer expires TimerCallback callback = new TimerCallback(ReloadWorkflow); TimeSpan timeDifference = subscription.ExpiresAt - DateTime.UtcNow; // check to make sure timeDifference is in legal range if (timeDifference > FilePersistenceService.MaxInterval) { timeDifference = FilePersistenceService.MaxInterval; } else if (timeDifference < TimeSpan.Zero) { timeDifference = TimeSpan.Zero; } this.instanceTimers.Add(contextGuid, new System.Threading.Timer( callback, subscription.WorkflowInstanceId, timeDifference, new TimeSpan(-1))); } }
public Timer(TimerCallback callback, object state, int dueTime, int period) { _callback = callback; _state = state; _period = period; Reset(dueTime); }
/// <summary> /// Object cache caches an object for a given cache time and raises an event when it's /// expired. /// </summary> /// <param name="cacheTime">Time to cache objects in micro seconds (1000 = 1sec)</param> public ObjectCache(long cacheTime) { items = new Hashtable(); expiries = new Hashtable(); timerTimeoutCallback = new TimerCallback(itemExpired); this.cacheTime = cacheTime; }
public void set(float interval, int repeat, TimerCallback callback, object param, bool useFrame) { this.interval = interval; this.repeat = repeat; this.callback = callback; this.param = param; }
public Timer (TimerCallback callback, object state, uint dueTime, uint period) { // convert all values to long - with a special case for -1 / 0xffffffff long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime; long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period; Init (callback, state, d, p); }
private void EcwOldSendAndReceive(){ ecwOldIsStandalone=true;//and for Mountainside if(Programs.UsingEcwTightOrFullMode()) { ecwOldIsStandalone=false; } //#if DEBUG//just so I don't forget to remove it later. //IsStandalone=false; //#endif ecwOldHl7FolderOut=PrefC.GetString(PrefName.HL7FolderOut); if(!Directory.Exists(ecwOldHl7FolderOut)) { throw new ApplicationException(ecwOldHl7FolderOut+" does not exist."); } //start polling the folder for waiting messages to import. Every 5 seconds. TimerCallback timercallbackReceive=new TimerCallback(EcwOldTimerCallbackReceiveFunction); ecwOldTimerReceive=new System.Threading.Timer(timercallbackReceive,null,5000,5000); if(ecwOldIsStandalone) { return;//do not continue with the HL7 sending code below } //start polling the db for new HL7 messages to send. Every 1.8 seconds. ecwOldHl7FolderIn=PrefC.GetString(PrefName.HL7FolderIn); if(!Directory.Exists(ecwOldHl7FolderIn)) { throw new ApplicationException(ecwOldHl7FolderIn+" does not exist."); } TimerCallback timercallbackSend=new TimerCallback(EcwOldTimerCallbackSendFunction); ecwOldTimerSend=new System.Threading.Timer(timercallbackSend,null,1800,1800); }
/// <summary> /// 処理延滞 /// </summary> /// <author>Takanori Shibuya</author> public void Delayed() { this.Dispose(); TimerCallback timerDelegate = new TimerCallback(CallbackHandle); this.timer = new Timer(timerDelegate, null, 0, this.delay); }
/// <summary> /// 一度だけ実行されるタイマを設定する /// </summary> /// <param name="callback">タイマコールバック関数</param> /// <param name="dueTime">開始までの時間.0で即時開始</param> /// <returns>生成されたタイマインスタンス</returns> public static Timer OnceTimer(TimerCallback callback, int dueTime) { if (dueTime < 0) return null; Trace.WriteLine("[" + DateTime.Now.ToString() + "] LabMonitoring.TimerUtil#OnceTimer\r\n" + "New timer is set after " + dueTime + " ms at once."); return new Timer(callback, null, dueTime, Timeout.Infinite); }
/// <summary> /// 開始日時を指定したタイマを設定する /// </summary> /// <param name="callback">タイマコールバック関数</param> /// <param name="startTime">実行開始日時</param> /// <param name="period">繰り返し間隔</param> /// <returns>生成されたタイマインスタンス</returns> public static Timer TimerWithStartTime(TimerCallback callback, DateTime startTime, TimeSpan period) { TimeSpan ts = startTime - DateTime.Now; Trace.WriteLine("[" + DateTime.Now.ToString() + "] LabMonitoring.TimerUtil#TimerWithStartTime\r\n" + "New timer is set at " + startTime.ToString() + " every " + period.Minutes + " minutes."); return new Timer(callback, null, ts, period); }
public Timer(float targetTime, TimerCallback timerCallback, float delay=0) { this.delay = delay; currentTime = targetTime; this.targetTime = targetTime; timerCallbackFunction = timerCallback; }
/// <summary> /// 一度だけ実行されるタイマを設定する /// </summary> /// <param name="callback">タイマコールバック関数</param> /// <param name="startTime">開始する日時</param> /// <returns>生成されたタイマインスタンス</returns> public static Timer OnceTimer(TimerCallback callback, DateTime startTime) { TimeSpan ts = startTime - DateTime.Now; Trace.WriteLine("[" + DateTime.Now.ToString() + "] LabMonitoring.TimerUtil#OnceTimer\r\n" + "New timer is set at " + startTime.ToString() + " at once."); return OnceTimer(callback, (int)ts.TotalMilliseconds); }
public static void StartSessionRefresh() { if (!IsSaasConnection) return; callback = new TimerCallback (Refresh); timer = new Timer (callback, null, 0, 300000); }
static void Main(string[] args) { TimerCallback callback = new TimerCallback(RequestService); Timer stateTimer = new Timer(callback, null, 0, 3000); for (; ; ) { } }
protected override void OnStart(string[] args) { //Below code fires once a second job = new CronJob(); timerDelegate = new TimerCallback(job.DoSomething); stateTimer = new Timer(timerDelegate, null, 1000, 1000); }
private void LoadView () { // Paste your license key here. mNChartView.Chart.LicenseKey = ""; // Margin to ensure some free space for the iOS status bar. mNChartView.Chart.CartesianSystem.Margin = new NChartTypes.Margin (10.0f, 10.0f, 10.0f, 20.0f); // Create column series with colors from the array and add them to the chart. NChartColumnSeries series = new NChartColumnSeries (); // Set brush that will fill that series with color. series.Brush = new NChartSolidColorBrush (Color.Argb (255, 100, 200, 225)); // Set data source for the series. series.DataSource = this; // Add series to the chart. mNChartView.Chart.AddSeries (series); // Activate streaming mode. mNChartView.Chart.StreamingMode = true; // Prevent minimum and maximum on the axes from "jumping" by activating incremental mode. So the minimum will remain // the minimal value ever appeared in the data, and maximum will remain the maximal one. mNChartView.Chart.IncrementalMinMaxMode = true; // Update data in the chart. mNChartView.Chart.UpdateData (); TimerCallback timerCallback = new TimerCallback (Stream); timer = new Timer (timerCallback, mNChartView.Chart.GetSeries () [mNChartView.Chart.GetSeries ().Length - 1], 100, 100); }
public static void Open(Action<Guid, int> received, TimerCallback onTimer) { _received = received; _onTimer = onTimer; int index = 0; List<Uri> actorUris = new List<Uri>(); using (TextReader reader = File.OpenText("Endpoints.txt")) { while (true) { string line = reader.ReadLine(); if (line == null) break; actorUris.Add(new Uri(line.ToLower().Replace("localhost", Environment.MachineName))); } } _endpoints = actorUris.ToArray(); for (int i = 0; i < _endpoints.Length; i++) { if (TryListening(i)) Console.WriteLine("* {0} {1}", index, _endpoints[i]); else Console.WriteLine(" {0} {1}", index, _endpoints[i]); }; _listener.BeginGetContext(OnRequest, null); }
private int timer_lock = 0; //定时器循环重复进入锁 #endregion Fields #region Constructors private CTaskManager_WuQi() { l_tasks = new List<CTask_WuQi>(); task_lock = new object(); timerDelegate = new TimerCallback(TimerMethod); ticker = new Timer(timerDelegate,this,30000,peroid); }
//need sync locking in this constructor? /// <summary> /// Private constructor, loads configuration, initializes the internal event queue /// and sets up the flush timer delegate. /// </summary> private Logger() { try { Debug.WriteLine("Creating Logger object.", "Logger.ctor"); m_oLoggerConfig = (LoggerConfig)LoggerUtils.XMLSerializer.DeserializeObjectFromFile(typeof(LoggerConfig), m_sConfigFile); m_qEvents = new Queue(); m_iFlushInterval = m_oLoggerConfig.FlushInterval; m_sAppSourceName = m_oLoggerConfig.AppName; m_oTimerCallback = new TimerCallback(m_oFlushDelegate.Flush); //m_oTimer = new Timer(m_oTimerCallback, null, m_iFlushInterval * 1000, m_iFlushInterval * 1000); //set the logger config object for the handler factory HandlerFactory.SetLoggerConfig(m_oLoggerConfig); } catch (IOException ioExp) { Debug.WriteLine("IOException while creating Logger(ctor). Logger will not log anything!: " + ioExp.Message, "Logger.ctor"); ExceptionWriter("IOException while creating Logger(ctor). Logger will not log anything!", ioExp); } catch (LoggerUtils.XMLSerializerException xmlExp) { Debug.WriteLine("XMLSerializerException while creating Logger(ctor). Logger will not log anything!: " + xmlExp.Message, "Logger.ctor"); ExceptionWriter("XMLSerializerException while creating Logger(ctor). Logger will not log anything!", xmlExp); } catch (Exception exp) { Debug.WriteLine("General exception while creating Logger(ctor). Logger will not log anything!: " + exp.Message, "Logger.ctor"); ExceptionWriter("General exception while creating Logger(ctor). Logger will not log anything!", exp); } }
/// <summary> /// init /// </summary> /// <param name="callback"></param> /// <param name="dueTime"></param> /// <param name="period"></param> /// <param name="executeTimeout"></param> public SyncTimer(TimerCallback callback, int dueTime, int period, int executeTimeout = 60000) { _callback = callback; DueTime = dueTime; Period = period; ExecuteTimeout = executeTimeout; }
public void Init() { BeforeHour = DateTime.Now.Hour; TimerCallback Mastertc = new TimerCallback(MasterCounter); Mastertimer = new Timer(Mastertc, null, 0, 1000); }
public ButtonPlus( int x, int y, int normalID, int pressedID, int buttonID, string name, TimerCallback back ) : base(x, y, normalID, pressedID, buttonID, GumpButtonType.Reply, 0) { c_Name = name; c_Callback = back; c_Param = ""; }
public void initializeTimer() { callBack = new TimerCallback(updateCB); timer = new System.Threading.Timer( callBack, DownloadQueueListBox, 0, 5000); }
public SmartTimer(TimerCallback callback, object state, TimeSpan due, TimeSpan period) { this.period = period; this.callback = callback; this.next = DateTime.UtcNow + due; this.timer = new Timer(new TimerCallback(this.HandleCallback), state, due, this.infinite); }
public TSK_Timer(UInt64 period, Boolean repeat, TimerCallback callback) { mPeriod = period; mRepeat = repeat; mTimer = new Timer(callback, this, Timeout.Infinite, Timeout.Infinite); }
public Timer(TimerCallback callback, object state, int dueTime, int period) { this.callback = callback; this.state = state; Change(dueTime, period); }
public static Timer RecurringCall(double delay, TimerCallback callback) { Timer newTimer = null; Timer returnTimer = null; try { newTimer = new Timer(delay); newTimer.AutoReset = true; 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> /// Constructor /// </summary> /// <param name="percussion">Percussion enumeration</param> /// <param name="sound">Cymbal sound</param> /// <param name="boundaries">Bounding box</param> /// <param name="touchAreas">List of rectangular touch areas</param> /// <param name="image">Cymbal image</param> public Cymbal(Percussion percussion, SoundEffect sound, Rectangle boundaries, List<Rectangle> touchAreas, Texture2D image) : base(percussion, sound, boundaries, touchAreas, image) { MaxAngle = 0.26f; // Default for max angle (~15 degrees) rotate = new TimerCallback(RotateCallback); Played += new EventHandler(Cymbal_Played); }
public void RunTimer() { TimeObject TimeObj = new TimeObject(); TimeObj.enable = true; TimeObj.count = 1; TimerCallback TimerDelegate = new TimerCallback(TimerTask); Timer TimerItem = new Timer(TimerDelegate, TimeObj, 2000, delay); TimeObj.timer = TimerItem; TimeSpan span1 = TimeSpan.FromMinutes(this.minutes); if (!infi) { while (TimeObj.count < max_count) { Thread.Sleep(span1); } } else { while (true) { Thread.Sleep(span1); } } TimeObj.enable = false; }
public DefaultKeepAliveTracker(TimeSpan keepAliveInterval, TimerCallback keepAliveCallback) { _keepAliveInterval = keepAliveInterval; _keepAliveTimerElapsedCallback = keepAliveCallback; _lastSendActivity = new Stopwatch(); _lastReceiveActivity = new Stopwatch(); }
public void SetCallback(TimerCallback callback) { if (_timer != null) _timer.Dispose(); _timer = new Timer(callback); }
public static void RunWithTimeout(Func <AsyncCallback, object, IAsyncResult> beginMethod, AsyncCallback callback, TimerCallback timeoutCallback, object state, TimeSpan timeout) { CommonUtility.AssertNotNull("beginMethod", beginMethod); CommonUtility.AssertNotNull("callback", callback); CommonUtility.AssertNotNull("timeoutCallback", timeoutCallback); APMWithTimeout operation = new APMWithTimeout(timeoutCallback); operation.Begin(beginMethod, callback, state, timeout); }
private Timer InternalCreateTimer(TimerMode mode, TimerExecutionContext context, TimerCallback callback, uint dueTime, uint period, bool isLongRunning) { Debug.Assert(_hQueue != IntPtr.Zero); if (_hQueue == IntPtr.Zero) { throw new InvalidOperationException("The timer queue has already been disposed."); } Debug.Assert(callback != null); if (callback == null) { throw new ArgumentNullException("callback"); } switch (mode) { case TimerMode.OneShot: Debug.Assert(dueTime > 0); Debug.Assert(period == 0); if (dueTime <= 0) { throw new ArgumentOutOfRangeException("dueTime", dueTime, "One-shot timers require a due time of 1ms or more."); } break; case TimerMode.Periodic: Debug.Assert(period > 0); if (period <= 0) { throw new ArgumentOutOfRangeException("period", period, "Periodic timers require a period of 1ms or more."); } break; } NativeMethods.TimerQueueFlags flags = (NativeMethods.TimerQueueFlags)(( uint )mode | ( uint )context); if (isLongRunning == true) { flags |= NativeMethods.TimerQueueFlags.WT_EXECUTELONGFUNCTION; } Timer timer = new Timer(this, mode, context, isLongRunning, dueTime, period, callback); lock ( _syncRoot ) { timer.Entry = _timers.Enqueue(timer); timer.ID = _timerId++; } IntPtr handle = IntPtr.Zero; bool result = NativeMethods.CreateTimerQueueTimer( ref handle, _hQueue, _delegate, new IntPtr(timer.ID), dueTime, period, flags); Debug.Assert(result == true); if (result == false) { lock (_syncRoot) _timers.Remove(timer.Entry); int error = Marshal.GetLastWin32Error(); throw new Win32Exception(error, "Unable to create timer instance."); } timer.Handle = handle; return(timer); }
internal Timer(TimerQueue queue, TimerMode mode, TimerExecutionContext context, bool isLongRunning, uint dueTime, uint period, TimerCallback callback) { Debug.Assert(queue != null); Debug.Assert(callback != null); Queue = queue; Mode = mode; ExecutionContext = context; IsLongRunning = isLongRunning; Period = period; DueTime = dueTime; Callback = callback; }
private static void Main(string[] args) { Console.Title = "Omes Qpu Version(MSsql) 2017.10.08"; try { OlayGunluk.Olay("MAIN (QPU) başlatıldı"); Console.WriteLine("##__________ MAIN (QPU) başlatıldı _________##\n"); //string[] ports = SerialPort.GetPortNames(); //foreach (string port in ports) //{ // SerialPort a = new SerialPort(port); // a.Open(); // if (a.IsOpen) // { // Console.WriteLine("Comport"+ port); // comPort = port; // break; // } //} if (args.Length > 0) { comPort = "COM" + args[0].Substring(1); Console.WriteLine("Com port COM" + args[0].Substring(1) + " olarak ayarlandı..."); OlayGunluk.Olay("Com port COM" + args[0].Substring(1) + " olarak ayarlandı..."); } else { comPort = "COM1"; Console.WriteLine("Com port COM1 olarak ayarlandı..."); OlayGunluk.Olay("Com port COM1 olarak ayarlandı..."); } if (DBProcess.GetCon2())//bağlantıyı kotrol et { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nSunucuya Bağlanıldı..\n"); OlayGunluk.Olay("Sunucuya Bağlanıldı.."); Console.ResetColor(); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\nSunucuya Bağlanılamadı.. \nSunucunun Açık olduğundan emin olup, Kullanıcı adı ve parolanızı kontrol ederek tekrar deneyiniz.\n"); OlayGunluk.Olay("Sunucuya Bağlanılamadı!..\n"); Console.ResetColor(); Console.Beep(); Console.ReadKey(); Environment.Exit(-1); //programdan çık } } catch (Exception hata1) { Console.WriteLine("Hata1:" + hata1.Message); OlayGunluk.Olay("Hata1:" + hata1.Message); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Com port bilgisi okunamadı, COM1 olarak ayarlandı...\n"); Console.ResetColor(); } try { Console.WriteLine("İşlem görmemiş biletler sistemden temizleniyor..."); if (CheckLeapTicket()) { Console.WriteLine("Temizleme işlemi başarıyla tamamlandı.\n"); } else { Console.WriteLine("Temizlenecek bilet bulunamadı.\n"); } Thread thrReadPort = new Thread(ListenStart); thrReadPort.Start(); Thread thrReadTCPIP = new Thread(ListenTCPIP); thrReadTCPIP.Start(); Thread thrReadLCD = new Thread(ListenTCPIPForLCD); thrReadLCD.Start(); //Console.WriteLine("kioskta butana basacak"); //Communicating.KiosktaOzelButonaBas(); //Console.WriteLine("kioskta butana bastı"); //Timer aa = new Timer(TimerCallback, null, 0, 1000); TimerCallback callback = new TimerCallback(TimerCallback); Console.WriteLine("Global ResetTimer başladı, program start time: {0}\n", DateTime.Now.ToString("HH:mm:ss")); // 5 saniyede bir çalışacak Timer stateTimer = new Timer(callback, null, 0, 1000); Console.ReadLine(); Communice.Dispose(); } catch (Exception hata2) { Console.WriteLine("Main HATA2:" + hata2.Message); OlayGunluk.Olay("Main HATA2:" + hata2.Message); } }
public SafeTimer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period) { callbackFunc = callback; safeTimerBase = new SafeTimerBase(callbackFunc, state, dueTime, period); }
public SafeTimer(TimerCallback callback, object state) { callbackFunc = callback; safeTimerBase = new SafeTimerBase(callbackFunc, state); }
private APMWithTimeout(TimerCallback timeoutCallback) { this.timeoutCallback = timeoutCallback; }
public Queue() { TimerCallback tmCallback = RemoveSpecificItem; Timer timer = new Timer(RemoveSpecificItem, "Wait 1.5 Seconds", 1500, 1500); }
public extern Timer(TimerCallback callback, Object state, int dueTime, int period);
public override ITimer CreateTimer(TimerCallback cb, TimeSpan timeOut, object state) { return(new WinStoreAsyncTimer(ThreadPoolTimer.CreateTimer(s => cb(s), timeOut))); }
public static Timer Create(TimerCallback callback, object?state, TimeSpan dueTime) => Create(callback, state, dueTime, Timeout.InfiniteTimeSpan);
public extern Timer(TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period);
public static Timer Create(TimerCallback callback, int dueTime) => Create(callback, dueTime, Timeout.Infinite);
/// <inheritdoc /> public void Initialize(TimerCallback callback, TimeSpan waitTime) => _timer = new Timer(callback, null, waitTime, waitTime);
internal static Timer DelayedCallback(TimeSpan delay, TimerCallback call) { return(new OneTimeTimer(delay, call)); }
public static Timer Create(TimerCallback callback, int dueTime, int period) => Create(callback, null, dueTime, period);
public SampleViewModel() { TimerCallback tm = new TimerCallback(UpdateProgress); Timer timer = new Timer(tm, 0, 0, 30); }
public StateTimeout(string timerName, long timeoutMilliseconds, TimerCallback callback) { _name = timerName; _dueTime = timeoutMilliseconds; _timeout = new Timer(callback, _name, Timeout.Infinite, Timeout.Infinite); }
/// <summary> /// 桌子对象 /// </summary> /// <param name="roomId"></param> /// <param name="tableId"></param> /// <param name="playerNum">人数</param> /// <param name="anteNum">底注</param> /// <param name="multipleNum">倍数</param> /// <param name="callback"></param> /// <param name="packNum">几副牌</param> public TableData(int roomId, int tableId, int playerNum, int anteNum, int multipleNum, TimerCallback callback, int packNum = 1) { _roomId = roomId; _tableId = tableId; _playerNum = playerNum; _anteNum = anteNum; _multipleNum = multipleNum; _packNum = packNum; _cardList = new List <int>(PackMaxNum * packNum); _backCardData = new List <int>(); _callOperation = new bool[playerNum + 1]; _outCardList = new List <CardData>(); _positions = new PositionData[playerNum]; for (int i = 0; i < playerNum; i++) { _positions[i] = new PositionData(i); } _timer = new Timer(callback, this, -1, -1); Init(); }
internal OneTimeTimer(TimeSpan d, TimerCallback call) : base(d) { m_Call = call; }
public abstract void Connect(TimerCallback connectionClosed);
public void SetupTimer(TimerCallback callback, TimeSpan trigger) { timer = new Timer(callback); UpdateInterval(trigger, true); }
public static TimerCallback ThunkCallback(TimerCallback callback) { return((new Fx.TimerThunk(callback)).ThunkFrame); }
private void AvEventsAfterDraw(IDisplay display, esriViewDrawPhase phase) { try { if (phase == esriViewDrawPhase.esriViewForeground) { GsExtension extension = GsExtension.GetExtension(); if ((extension.InsideScale()) && (!_point.IsEmpty)) { // ReSharper disable UseIndexedProperty // ReSharper disable CSharpWarnings::CS0612 display.StartDrawing(display.hDC, (short)esriScreenCache.esriNoScreenCache); IDisplayTransformation dispTrans = display.DisplayTransformation; const float arrowSizeh = ((float)ArrowSize) / 2; double size = dispTrans.FromPoints(arrowSizeh); double angleh = (_hFov * Math.PI) / 360; double angle = (((450 - _angle) % 360) * Math.PI) / 180; double angle1 = angle - angleh; double angle2 = angle + angleh; double x = _point.X; double y = _point.Y; IPoint point1 = new PointClass { X = x, Y = y }; IPoint point2 = new PointClass { X = x + (size * Math.Cos(angle1)), Y = y + (size * Math.Sin(angle1)) }; IPoint point3 = new PointClass { X = x + (size * Math.Cos(angle2)), Y = y + (size * Math.Sin(angle2)) }; IPolygon4 polygon = new PolygonClass(); var polygonPoint = polygon as IPointCollection4; polygonPoint.AddPoint(point1); polygonPoint.AddPoint(point2); polygonPoint.AddPoint(point3); polygonPoint.AddPoint(point1); IColor color = Converter.ToRGBColor(_color); color.Transparency = _blinking ? BlinkAlpha : NormalAlpha; color.UseWindowsDithering = true; var fillSymbol = new SimpleFillSymbolClass { Color = color, Outline = null }; display.SetSymbol(fillSymbol); display.DrawPolygon(polygon); IPolyline polyline = new PolylineClass(); var polylinePoint = polyline as IPointCollection4; polylinePoint.AddPoint(point2); polylinePoint.AddPoint(point1); polylinePoint.AddPoint(point3); var outlineSymbol = new SimpleLineSymbolClass { Color = Converter.ToRGBColor(_active ? Color.Yellow : Color.Gray), Width = _blinking ? BorderSizeBlinkingArrow : BorderSizeArrow }; display.SetSymbol(outlineSymbol); display.DrawPolyline(polyline); display.FinishDrawing(); if (_blinking) { var blinkEvent = new AutoResetEvent(true); var blinkTimerCallBack = new TimerCallback(ResetBlinking); _blinkTimer = new Timer(blinkTimerCallBack, blinkEvent, BlinkTime, -1); } // ReSharper restore CSharpWarnings::CS0612 // ReSharper restore UseIndexedProperty } } } catch (Exception ex) { Trace.WriteLine(ex.Message, "Arrow.avEventsAfterDraw"); } }
public void FindAsync() { const string multicastIP = "239.255.255.250"; const int multicastPort = 1900; const int unicastPort = 1901; const int MaxResultSize = 8000; string find = "M-SEARCH * HTTP/1.1\r\n" + "HOST: 239.255.255.250:1900\r\n" + "MAN: \"ssdp:discover\"\r\n" + "MX: " + maximumWait.ToString() + "\r\n" + "ST: " + searchTarget + "\r\n" + "\r\n"; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); byte[] MulticastData = Encoding.UTF8.GetBytes(find); socket.SendBufferSize = MulticastData.Length; SocketAsyncEventArgs sendEvent = new SocketAsyncEventArgs(); sendEvent.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(multicastIP), multicastPort); sendEvent.SetBuffer(MulticastData, 0, MulticastData.Length); sendEvent.Completed += new EventHandler <SocketAsyncEventArgs>((sender, e) => { if (e.SocketError == SocketError.OperationAborted) { } else if (e.SocketError != SocketError.Success) { Debug.WriteLine("Socket error {0}", e.SocketError); } else { if (e.LastOperation == SocketAsyncOperation.SendTo) { // When the initial multicast is done, get ready to receive responses e.RemoteEndPoint = new IPEndPoint(IPAddress.Any, unicastPort); socket.ReceiveBufferSize = MaxResultSize; byte[] receiveBuffer = new byte[MaxResultSize]; e.SetBuffer(receiveBuffer, 0, MaxResultSize); socket.ReceiveFromAsync(e); } else if (e.LastOperation == SocketAsyncOperation.ReceiveFrom) { // Got a response, so decode it var result = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred); var headers = ParseSsdpResponse(result); if (headers != null) { Debug.WriteLine(result); OnResponseReceived(new ResponseReceivedEventArgs(headers, (e.RemoteEndPoint as IPEndPoint).Address)); } else { Debug.WriteLine("INVALID SEARCH RESPONSE"); } // And kick off another read try { socket.ReceiveFromAsync(e); } catch (ObjectDisposedException) { } } } }); // Kick off the initial Send socket.SendToAsync(sendEvent); // Set a one-shot timer for double the Search time, to be sure we are done before we stop everything TimerCallback cb = new TimerCallback((state) => { socket.Close(); timer.Dispose(); timer = null; // BUGBUG: we can still be in sendEvent.Completed on another thread OnDiscoveryCompleted(); }); timer = new Timer(cb, timer, (maximumWait * 2) * 1000, Timeout.Infinite); }
public YoloTimer(TimerCallback callback, object state) { _callback = callback; _timer = new Timer(OnCallback, state, Timeout.Infinite, Timeout.Infinite); }
private void configure() { #if DEBUG _ws.Log.Level = LogLevel.Trace; #endif _ws.OnOpen += (sender, e) => { var msg = createTextMessage("connection", String.Empty); _ws.Send(msg); }; _ws.OnMessage += (sender, e) => { switch (e.Type) { case Opcode.Text: var msg = parseTextMessage(e.Data); _msgQ.Enqueue(msg); break; case Opcode.Binary: var audioMsg = parseAudioMessage(e.RawData); if (audioMsg.user_id == _user_id) { goto default; } if (_audioBox.ContainsKey(audioMsg.user_id)) { _audioBox[audioMsg.user_id].Enqueue(audioMsg.buffer_array); } else { var q = Queue.Synchronized(new Queue()); q.Enqueue(audioMsg.buffer_array); _audioBox.Add(audioMsg.user_id, q); } break; default: break; } }; _ws.OnError += (sender, e) => { enNfMessage("[AudioStreamer] error", "WS: Error: " + e.Message, "notification-message-im"); }; _ws.OnClose += (sender, e) => { enNfMessage ( "[AudioStreamer] disconnect", String.Format("WS: Close({0}: {1})", e.Code, e.Reason), "notification-message-im" ); }; //_ws.Compression = CompressionMethod.Deflate; _notifyMsgState = new ThreadState(); _notifyMsg = (state) => { while (_notifyMsgState.Enabled || _msgQ.Count > 0) { Thread.Sleep(500); if (_msgQ.Count > 0) { NfMessage msg = (NfMessage)_msgQ.Dequeue(); #if NOTIFY Notification nf = new Notification(msg.Summary, msg.Body, msg.Icon); nf.AddHint("append", "allowed"); nf.Show(); #else Console.WriteLine("{0}: {1}", msg.Summary, msg.Body); #endif } } _notifyMsgState.Notification.Set(); }; _sendHeartbeat = (state) => { var msg = createTextMessage("heartbeat", String.Empty); _ws.Send(msg); }; }
public Timer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period) : this(callback, state, (int)dueTime.TotalMilliseconds, (int)period.TotalMilliseconds) { }
/// <summary> /// Retrieves the count of detected faces /// </summary> /// <param name="faces">The list of detected faces from the FaceDetected event of the effect</param> private async void CountDetectedFaces(IReadOnlyList <DetectedFace> faces) { FaceCount = $"{_detectionString} {faces.Count.ToString()}"; // If we detect any faces, kill our no faces timer if (faces.Count != 0) { if (_noFacesTimer != null) { _noFacesTimer.Dispose(); } } // Otherwise, if we are filtering and don't have a timer else if (_currentlyFiltered && (_noFacesTimer == null)) { // Create a callback TimerCallback noFacesCallback = (object stateInfo) => { _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { OnFilterOnFace(_unfilteredName); _noFacesTimer = null; }); _noFacesTimer.Dispose(); }; // Set our timer _noFacesTimer = new Timer(noFacesCallback, null, NoFacesTime, Timeout.Infinite); } // We are also going to take an image the first time that we detect exactly one face. // Sidenote - to avoid a race-condition, I had to use a boolean. Just checking for _faceCaptureStill == null could produce an error. if ((faces.Count == 1) && !_holdForTimer && !_currentlyFiltered) { // Kick off the timer so we don't keep taking pictures, but will resubmit if we are not filtered _holdForTimer = true; // Take the picture _faceCaptureStill = await ApplicationData.Current.LocalFolder.CreateFileAsync("FaceDetected.jpg", CreationCollisionOption.ReplaceExisting); await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), _faceCaptureStill); if (((App)Application.Current).AppSettings.FaceApiKey != "" && FacialSimilarity.InitialTrainingPerformed) { var UserName = await FacialSimilarity.CheckForUserAsync(new Uri("ms-appdata:///local/FaceDetected.jpg")); if (UserName != "") { OnFilterOnFace(UserName); } } // Allow the camera to take another picture in 10 seconds TimerCallback callback = (Object stateInfo) => { // Now that the timer is expired, we no longer need to hold // Nothing else to do since the timer will be restarted when the picture is taken _holdForTimer = false; if (_pictureTimer != null) { _pictureTimer.Dispose(); } }; _pictureTimer = new Timer(callback, null, 10000, Timeout.Infinite); } }
public DeviceMapEntry(DeviceStatus status, TimerCallback entryExpiredCallback) { LastStatus = status; expiryTimer = new Timer(entryExpiredCallback, this, Timeout.Infinite, Timeout.Infinite); }