Dispose() public method

public Dispose ( System notifyObject ) : bool
notifyObject System
return bool
コード例 #1
0
 private void OnNorthGuideTimer(Object stateInfo)
 {
     Request(":Qn#");
     northGuideBusy = false;
     northGuideTimer?.Dispose();
     northGuideTimer = null;
 }
コード例 #2
0
 private void OnWestGuideTimer(Object stateInfo)
 {
     Request(":Qw#");
     westGuideBusy = false;
     westGuideTimer?.Dispose();
     westGuideTimer = null;
 }
コード例 #3
0
        }// OnDataReceived

        #endregion serial communication

        #region Guide timer callback methods

        private void OnEastGuideTimer(Object stateInfo)
        {
            Request(":Qe#");
            eastGuideBusy = false;
            eastGuideTimer?.Dispose();
            eastGuideTimer = null;
        }
コード例 #4
0
 private void OnSouthGuideTimer(Object stateInfo)
 {
     Request(":Qs#");
     southGuideBusy = false;
     southGuideTimer?.Dispose();
     southGuideTimer = null;
 }
コード例 #5
0
ファイル: Form1.cs プロジェクト: mulykr/graphicsLab01
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                t?.Dispose();

                double a = double.Parse(this.A.Text);
                double b = double.Parse(this.B.Text);
                double c = double.Parse(this.C.Text);

                sXc   = float.Parse(this.sX.Text);
                sYc   = float.Parse(this.sY.Text);
                sideS = float.Parse(this.side.Text);

                rect        = new Shapes.Rectangle(new Shapes.Point(sXc - sideS, sYc - sideS), new Shapes.Point(sXc + sideS, sYc - sideS), new Shapes.Point(sXc + sideS, sYc + sideS), new Shapes.Point(sXc - sideS, sYc + sideS));
                rect.Center = new Shapes.Point(sXc, sYc);
                line        = new Line((x) => (-(a / b) * x - c / b));

                kPerp = b / a;
                perp  = new Line((x) => (b / a) * (x - sXc) + sYc);


                graphics.Clear(Color.White);

                CrossPoint();

                if (kx <= sXc && ky <= sYc)
                {
                    moveKx = -1;
                    moveKy = -1;
                }
                else if (kx <= sXc && ky >= sYc)
                {
                    moveKx = -1;
                    moveKy = 1;
                }
                else if (kx >= sXc && ky <= sYc)
                {
                    moveKx = 1;
                    moveKy = -1;
                }
                else if (kx >= sXc && ky >= sYc)
                {
                    moveKx = 1;
                    moveKy = 1;
                }
                else
                {
                    throw new ArgumentException("Incorrect data!");
                }

                t = new System.Threading.Timer(new TimerCallback((object o) => { this.graphics.Clear(Color.White); DrawLine(); DrawSquare(); this.canvas.Image = bmp; }), 0, 1000, 1);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
                MessageBox.Show(exc.StackTrace);
            }
        }
コード例 #6
0
        /// <summary>
        /// 播放图片
        /// </summary>
        /// <param name="model"></param>
        private void PlayPic(AppModel model)
        {
            picIndex = 0;
            this.Invoke(new Action(() =>
            {
                this.pictureBox1.Dock    = DockStyle.Fill;
                this.pictureBox1.Visible = true;
            }));

            picPlayTimer?.Dispose();
            InitPicPlayTimer();
        }
コード例 #7
0
        /// <summary>
        /// close the socket and any resources left
        /// </summary>
        public void Disconnected()
        {
            try
            {
                if (ListViewItem != null)
                {
                    SafeThreading.UIThread.Invoke((MethodInvoker) delegate
                    {
                        Interlocked.Decrement(ref Configuration.ConnectedClients);
                        lock (SafeThreading.SyncMainFormListview)
                        {
                            ListViewItem.Remove();
                            ListViewItem = null;
                            SafeThreading.UIThread.Text = $"MassRAT | By NYAN CAT | Online{Configuration.ConnectedClients}";
                        }
                    });
                }

                CurrentForms?.Cleanup();
                CurrentForms = null;

                Socket?.Dispose();

                KeepAlivePacket?.Dispose();
                Buffer = null;

                Debug.WriteLine("Disconnected");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
コード例 #8
0
        public void Work()
        {
            _charactersControl.CharacterSelected += character =>
            {
                _charactersControl.Hide();
                if (CharacterSelected != null)
                    CharacterSelected(character);
            };

            _charactersControl.DeleteCharacter += character =>
            {
                DI.Get<IGetStringControl>().Show("Удаление персонажа",
                    "Введите имя удаляемого персонажа.",
                    charName => character.Name == charName ? string.Empty : "Неправильное имя персонажа",
                    charName => { DeleteCharacter(character); });
            };

            _charactersControl.CancelDeleteCharacter += CancelDeleteCharacter;

            _timer = new Timer(state => {
                UpdateCharacters();
            },
                null,
                Settings.Default.CharactersRefreshInterval,
                Settings.Default.CharactersRefreshInterval);
            _charactersControl.ControlClosed += () => {
                if (_timer != null)
                    _timer.Dispose();
            };

            _charactersControl.Show(UpdateCharacters);
        }
コード例 #9
0
        public static void Method_2()
        {
            try
            {
                TimerCallback t = new TimerCallback(Method_1);
                Timer tmr = new Timer(t);
                ConsoleKeyInfo cki = new ConsoleKeyInfo();

                tmr.Change(0, 1);
                Console.WriteLine("Press UP Arrow");
                cki = Console.ReadKey();
                if (cki.Key == ConsoleKey.UpArrow)
                {
                    tmr.Dispose();
                    if(miliseconds > 300)
                    {
                    Console.WriteLine("Looser!!!");
                    }
                }
                Console.WriteLine("Result = {0} milisecond", miliseconds);
                while (true)
                {
                    if (cki.Key == ConsoleKey.UpArrow)
                    {
                        break;

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #10
0
ファイル: ByflyTools.cs プロジェクト: CoffeeNova/bfbalance
        /// <summary>
        /// Считает время ожидания ответа на запрос к http серверу
        /// </summary>
        /// <param name="address">Url адрес</param>
        /// <param name="maxRequestTime">Максимальное время ожидания ответа. -1 для бесконечного времени ожидания.</param>
        /// <returns>Время запроса в мс</returns>

        internal static int GetRequestTime(string address, RequestParams requestParams, int maxRequestTime, out Exception outEx)
        {
            int result = -1;
            Exception innerEx = null;
            using (var request = new HttpRequest())
            {
                request.UserAgent = HttpHelper.ChromeUserAgent();
                EventWaitHandle wh = new AutoResetEvent(false);
                var requestThread = new Thread(() =>
                {
                    var watch = new Stopwatch();
                    watch.Start();
                    try
                    {
                        string resultPage = request.Get(address, requestParams).ToString();
                    }
                    catch (Exception ex) { innerEx = ex; }
                    result = Convert.ToInt32(watch.ElapsedMilliseconds);
                    watch.Reset();
                    wh.Set();
                });
                requestThread.Start();
                var stoptimer = new System.Threading.Timer((Object state) =>
                {
                    requestThread.Abort();
                    wh.Set();
                }, null, maxRequestTime, Timeout.Infinite);
                wh.WaitOne();

                stoptimer.Dispose();
            }
            outEx = innerEx;
            return result;
        }
コード例 #11
0
ファイル: RaceViewer.cs プロジェクト: squimmy/SnailRace
        public void ShowRace(IRace race)
        {
            int turn = 0;
            this.drawTrack(race, turn, "Press any key to start the race...");
            Console.ReadKey(true);

            using (Timer timer = new System.Threading.Timer(
                (o) =>
                {
                    turn++;
                    this.drawTrack(race, turn, "(Press any key to skip)");
                }
            ))
            {
                timer.Change(this.speed, this.speed);

                while (turn < race.TurnCount - 1 && !Console.KeyAvailable) ; // check if race is finished or if there's anything in the input buffer
                while (Console.KeyAvailable)
                {
                    Console.ReadKey(true);	// clear the input buffer
                }
                timer.Dispose();
            }
            this.drawTrack(race, race.TurnCount - 1, string.Format("The winner is {0}\n\n", race.Winner.Name) + this.leftMargin + "Press any key to continue...");
            Console.ReadKey(true);
        }
コード例 #12
0
ファイル: WorkerRole.cs プロジェクト: laurikoobas/Azure
        public override void Run()
        {
            Trace.TraceInformation("Worker started processing of messages");

            // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
            Client.OnMessage((msg) =>
                {
                    Timer renewTimer = new Timer(UpdateLock, msg, 1000, updateLockLeaseInMilliSec); //every 30 seconds after 1 sec
                    try
                    {
                        // Process the message
                        Trace.TraceInformation("Processing Service Bus message: " + msg.SequenceNumber.ToString());
                        string reportReq = (string)msg.Properties["reportReq"];
                            if (!CreateReport(reportReq))
                                msg.DeadLetter();
                        msg.Complete();
                    }
                    catch (Exception e)
                    {
                        // Handle any message processing specific exceptions here
                        Trace.TraceError("Message processing exception: " + e.Message);
                        msg.Abandon();
                    }
                    renewTimer.Dispose();
                });

            CompletedEvent.WaitOne();
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: FuriousLogic/DelayRepay
 static void Main(string[] args)
 {
     Console.WriteLine("Main thread: starting a timer");
     Timer t = new Timer(DoSomething, 0, 0, (60 * 1000));
     Console.ReadLine();
     t.Dispose(); // Cancel the timer now
 }
コード例 #14
0
        static void Main(string[] args)
        {
            // Create an event to signal the timeout count threshold in the timer callback.
            AutoResetEvent autoEvent = new AutoResetEvent(false);

            StatusChecker statusChecker = new StatusChecker(10);

            // Create an inferred delegate that invokes methods for the timer.
            TimerCallback tcb = statusChecker.CheckStatus;

            // Create a timer that signals the delegate to invoke CheckStatus after one second, 
            // and every 1/4 second thereafter.
            Console.WriteLine("{0} Creating timer.\n", DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);

            // When autoEvent signals, change the period to every  1/2 second.
            autoEvent.WaitOne(5000, false);
            stateTimer.Change(0, 500);
            Console.WriteLine("\nChanging period.\n");

            // When autoEvent signals the second time, dispose of the timer.
            autoEvent.WaitOne(5000, false);
            stateTimer.Dispose();
            Console.WriteLine("\nDestroying timer.");
        }
コード例 #15
0
        //Let's talk with the client!
        private void SocketListenerThreadStart()
        {
            int size = 0; 
            //1KB buffer is enough?
            Byte[] byteBuffer = new Byte[1024];

            _lastReceiveDateTime = DateTime.Now;
            _currentReceiveDateTime = DateTime.Now;
            int _timeout = 10 * 60 * 1000; //10min of timeout
            Timer t = new Timer(new TimerCallback(CheckClientCommInterval), null, _timeout, _timeout);

            while (!_stopClient)
            {
                try
                {
                    size = _clientSocket.Receive(byteBuffer);
                    _currentReceiveDateTime = DateTime.Now;
                    parseClientCMD(byteBuffer, size);
                }
                catch (SocketException)
                {
                    //there are problems...better delete the connection
                    _stopClient = true;
                    _markedForDeletion = true;
                }
            }
            t.Dispose();
            t = null;
        }
コード例 #16
0
 static void Main(string[] args)
 {
     Timer t = new Timer(TimerMethod, null, 0, 1000);
     Console.WriteLine("Main thread {0} continue...", Thread.CurrentThread.ManagedThreadId);
     Thread.Sleep(10000);
     t.Dispose();
 }
コード例 #17
0
        private void ExecuteWebRequest(string url, Action<string> callback, Action<Exception> error)
        {
            WebClient webClient = new WebClient();

              // create a timeout timer
              Timer timer = null;
              TimerCallback timerCallback = state =>
              {
            timer.Dispose();
            webClient.CancelAsync();
            error(new TimeoutException());
              };
              timer = new Timer(timerCallback, null, 5000, 5000);

              // create a web client
              webClient.DownloadStringCompleted += (s, e) =>
              {
            timer.Dispose();
            try
            {
              string result = e.Result;
              _marshal.Invoke(() => callback(result));
            }
            catch (Exception ex)
            {
              _marshal.Invoke(() => error(ex));
            }
              };

              webClient.DownloadStringAsync(new Uri(url));
        }
コード例 #18
0
ファイル: MailWorker.cs プロジェクト: risedphantom/MassMailer
        public void Worker()
        {
            if (Config.CoreTest != 0)
                Logger.Log.Warn("Running in CoreTest mode ({0})", Config.CoreTest);

            SendCounter.Refresh();
            ErrorCounter.Refresh();
            LastSendCount = 0;
            LastErrorCount = 0;

            var timer = new Timer(GetStatus, null, 0, Config.NotifyPeriod * 1000);

            do
            {
                ProcessMassMail();
                Thread.Sleep(2000);

                //Trigger GC to reduce LOH fragmentation
                GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                GC.Collect();
            }
            while (!_threadStop);

            timer.Dispose();
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: JohnEffo/EasyNetQ
        public static void Main(string[] args)
        {
            var logger = new NoDebugLogger();

            var bus = RabbitHutch.CreateBus("host=localhost",
                x => x.Register<IEasyNetQLogger>(_ => logger));

            int messageCount = 0;
            var timer = new Timer(state =>
            {
                Console.Out.WriteLine("messages per second = {0}", messageCount);
                Interlocked.Exchange(ref messageCount, 0);
            }, null, 1000, 1000);

            bus.Subscribe<TestPerformanceMessage>("consumer", message => Interlocked.Increment(ref messageCount));

            Console.CancelKeyPress += (source, cancelKeyPressArgs) =>
            {
                Console.Out.WriteLine("Shutting down");
                bus.Dispose();
                timer.Dispose();
                Console.WriteLine("Shut down complete");
            };

            Thread.Sleep(Timeout.Infinite);
        }
コード例 #20
0
 static ImageLoader()
 {
     _expirationTimer = new Timer(_ => RemoveExpiredCaches(), null,
         TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
     App.ApplicationFinalize += () => _expirationTimer.Dispose();
     StartDecodeThread();
 }
コード例 #21
0
ファイル: Program.cs プロジェクト: tetianakr/GarbageCollector
        static void Main(string[] args)
        {
            var timer = new Timer(Method, "Hello", 0, 200);

            Console.ReadKey();
            timer.Dispose();
        }
コード例 #22
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _initialTimeoutTimer?.Dispose();
                    _blockTouchDelayTimer?.Dispose();
                    _pointerInputTargetWindow?.Dispose();
                    _inputProvider?.Dispose();
                    _surfaceForm?.Dispose();
                }
                _surfaceForm = null;

                SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
                if (_hWinEventHook != IntPtr.Zero)
                {
                    UnhookWinEvent(_hWinEventHook);
                }
                if (_winEventGch.IsAllocated)
                {
                    _winEventGch.Free();
                }

                disposedValue = true;
            }
        }
コード例 #23
0
        public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken = default(CancellationToken)) {
            // Validate arguments
            if (factory == null)
                throw new ArgumentNullException(nameof(factory));
            if (millisecondsDelay < 0)
                throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));

            // Create the timed task
            var tcs = new TaskCompletionSource<object>(factory.CreationOptions);
            var ctr = default(CancellationTokenRegistration);

            // Create the timer but don't start it yet.  If we start it now,
            // it might fire before ctr has been set to the right registration.
            var timer = new Timer(self => {
                // Clean up both the cancellation token and the timer, and try to transition to completed
                ctr.Dispose();
                (self as Timer)?.Dispose();
                tcs.TrySetResult(null);
            }, null, -1, -1);

            // Register with the cancellation token.
            if (cancellationToken.CanBeCanceled) {
                // When cancellation occurs, cancel the timer and try to transition to canceled.
                // There could be a race, but it's benign.
                ctr = cancellationToken.Register(() => {
                    timer.Dispose();
                    tcs.TrySetCanceled();
                });
            }

            // Start the timer and hand back the task...
            timer.Change(millisecondsDelay, Timeout.Infinite);
            return tcs.Task;
        }
コード例 #24
0
ファイル: SipUtil.cs プロジェクト: HNeukermans/Hallo
 public static void DisposeTimer(Timer timer)
 {
     Check.Require(timer, "timer");
     var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
     timer.Dispose(waitHandle);
     waitHandle.WaitOne(1000);
 }
コード例 #25
0
        public void AddTask(
            string taskName,
            Action task,
            TimeSpan dueTime,
            TimeSpan period,
            TaskConcurrencyOptions taskConcurrencyOptions)
        {
            var scheduledTask = new ScheduledTask(taskName, task, taskConcurrencyOptions);

              var taskTimer =
            new Timer(
              RunTask,
              scheduledTask,
              Timeout.Infinite,
              Timeout.Infinite);

              if (!_tasksTimers.TryAdd(taskName, taskTimer))
              {
            taskTimer.Dispose();

            throw new Exception("Could not add task " + taskName + ".");
              }

              taskTimer.Change(dueTime, period);
        }
コード例 #26
0
        private void ExecuteWebRequest(string url, Action<string> callback, Action<Exception> error)
        {
            //WebClient webClient = new WebClient();
              MvxRestRequest request = new MvxRestRequest(url);

              // create a timeout timer
              Timer timer = null;
              TimerCallback timerCallback = state =>
              {
              timer.Dispose();

              //Doesnt appear to be a way to cancel the request...   webClient.CancelAsync();
              error(new TimeoutException());
              };
              timer = new Timer(timerCallback, null, 5000, 5000);

              _restClient.MakeRequest(request, (MvxStreamRestResponse response) =>
              {
              timer.Dispose();
              StreamReader reader = new StreamReader(response.Stream);
              string result = reader.ReadToEnd();
              _marshal.Invoke(() => callback(result));
              }

              ,
              exception =>
              {
                  timer.Dispose();
                  _marshal.Invoke(() => error(exception));
              }
              );
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: ChrisChen3121/MySourceLib
 private static void ThreadingTimer()
 {
     Console.WriteLine("StartTimer {0:T}", DateTime.Now);
     Timer t1 = new Timer(TimeAction, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(3));
     Thread.Sleep(15000);
     t1.Dispose();
 }
コード例 #28
0
 /// <summary>
 /// Releases the managed and unmanaged resources used by the <see cref="AsyncTcpClient"/>.
 /// Closes the connection to the remote host and disabled automatic reconnecting.
 /// </summary>
 public void Dispose()
 {
     AutoReconnect = false;
     tcpClient?.Dispose();
     HeartBeatTimer?.Dispose();
     stream = null;
 }
コード例 #29
0
 static AccountViewModel()
 {
     tickCall = new Timer(
         _ => TimeTickCall.Raise(EventArgs.Empty),
         null, 0, 20 * 1000);
     ThreadHelper.Halt += () => tickCall.Dispose();
 }
コード例 #30
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         timer?.Dispose();
         CleaEndPoints();
     }
 }
コード例 #31
0
        static void Main(string[] args)
        {
            CreateBase();

            Timer timer = new Timer(new TimerCallback(Program.RealTimeTest), null, 0, 2000);
            Console.ReadLine();
            timer.Dispose();
        }
コード例 #32
0
ファイル: Timer.cs プロジェクト: DominikHerold/Schwimmkurs
        public void Dispose()
        {
            Stop();
            _taskTimer?.Dispose();

            _taskTimer = null;
            Elapsed    = null;
        }
コード例 #33
0
        public IDisposable StartSystemTimer(TimeSpan interval, Action tick)
        {
            var timer = new Timer(delegate
            {

            }, null, interval, interval);
            return Disposable.Create(() => timer.Dispose());
        }
コード例 #34
0
ファイル: Program.cs プロジェクト: xs2ranjeet/13ns9-1spr
        static void Main(string[] args)
        {
            Timer t = new Timer(TimerMethod, null, 0, 1000);

            Console.WriteLine("Основной поток {0} продолжается...", Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(5000);
            t.Dispose();
        }
コード例 #35
0
        /// <summary>
        /// 画面が閉じるときにMvvmCrossから呼ばれます。
        /// </summary>
        public override void ViewDisappeared()
        {
            // タイマー破棄
            _timer?.Dispose();
            _timer = null;

            base.ViewDisappeared();
        }
コード例 #36
0
ファイル: Program.cs プロジェクト: matt-softlogic/samples
        public static void SendData(string serviceBusConnectionString, string entryHubName, string exitHubName)
        {
            var entryEventHub = EventHubClient.CreateFromConnectionString(serviceBusConnectionString, entryHubName);
            var exitEventHub = EventHubClient.CreateFromConnectionString(serviceBusConnectionString, exitHubName);
           
            var timerInterval = TimeSpan.FromSeconds(1);
            var generator = TollDataGenerator.Generator();

            TimerCallback timerCallback = state =>
            {
                var startTime = DateTime.UtcNow;
                generator.Next(startTime, timerInterval, 5);

                foreach (var e in generator.GetEvents(startTime))
                {
                    if (e is EntryEvent)
                    {
                        entryEventHub.Send(
                           new EventData(Encoding.UTF8.GetBytes(e.Format()))
                                    {
                                        PartitionKey = e.TollId.ToString(CultureInfo.InvariantCulture)
                                    });
                    }
                    else
                    {
                        exitEventHub.Send(
                           new EventData(Encoding.UTF8.GetBytes(e.Format()))
                           {
                               PartitionKey = e.TollId.ToString(CultureInfo.InvariantCulture)
                           });
                    }
                }

                timer.Change((int)timerInterval.TotalMilliseconds, Timeout.Infinite);
            };

            timer = new Timer(timerCallback, null, Timeout.Infinite, Timeout.Infinite);
            timer.Change(0, Timeout.Infinite);

            Console.WriteLine("Sending event hub data... Press Ctrl+c to stop.");

            var exitEvent = new ManualResetEvent(false);
            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Console.WriteLine("Stopping...");
                eventArgs.Cancel = true;
                exitEvent.Set();
            };

            exitEvent.WaitOne();
            Console.WriteLine("Shutting down all resources...");
            timer.Change(Timeout.Infinite, Timeout.Infinite);
            Thread.Sleep(timerInterval);
            timer.Dispose();
            entryEventHub.Close();
            exitEventHub.Close();
            Console.WriteLine("Stopped.");
        }
コード例 #37
0
ファイル: Program.cs プロジェクト: shumakosik/qweqwe
        static void work(int ind)
        {
            Timer t = new Timer(new TimerCallback(clientDel), ind, 1000, 1000);
            while (b)
            {

            }
            t.Dispose();
        }
コード例 #38
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         FlushQueue(null);
         _flushTimer?.Dispose();
         _idleTimer?.Dispose();
     }
 }
コード例 #39
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources, otherwise false to release unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                timer?.Dispose();
            }

            disposed = true;
        }
コード例 #40
0
ファイル: SystemRefresher.cs プロジェクト: nono3551/paco
        public Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("SystemRefresh is stopping.");

            _timer?.Change(Timeout.Infinite, 0);
            _timer?.Dispose();

            return(Task.CompletedTask);
        }
コード例 #41
0
ファイル: Program.cs プロジェクト: qratosone/CSharp
 static void Main(string[] args)
 {
     Console.WriteLine("Press any key to stop");
     TaskInfo ti = new TaskInfo();
     //创建一个Timer对象,然后把一个回调函数传给他
     Timer tm = new Timer(ShowTime, ti, 0, 1000);
     Console.ReadKey();
     tm.Dispose();
 }
コード例 #42
0
 static void Main(string[] args)
 {
     System.Console.WriteLine("敲任意键结束……");
       TaskInfo ti=new TaskInfo() ;
       //创建Timer对象,将一个回调函数传给它,每隔一秒调用一次
       Timer tm = new Timer(ShowTime, ti , 0, 1000);
       System.Console.ReadKey();
       tm.Dispose();
 }
コード例 #43
0
        protected override void OnDisappearing()
        {
            base.OnDisappearing();

            _calcTimer?.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
            _calcTimer?.Dispose();

            REnv.SaveValue();
        }
コード例 #44
0
        static void Main(string[] args)
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            string cefPath             = Path.Combine(Path.GetDirectoryName(GetProjectPath()), "cef");
            bool   externalMessagePump = args.Contains("--external-message-pump");

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;

            var settings = new CefSettings();

            settings.MultiThreadedMessageLoop = !externalMessagePump;
            settings.ExternalMessagePump      = externalMessagePump;
            settings.NoSandbox = true;
            settings.WindowlessRenderingEnabled = true;
            settings.LocalesDirPath             = Path.Combine(cefPath, "Resources", "locales");
            settings.ResourcesDirPath           = Path.Combine(cefPath, "Resources");
            settings.LogSeverity                = CefLogSeverity.Warning;
            settings.IgnoreCertificateErrors    = true;
            settings.UncaughtExceptionStackSize = 8;

            var app = new CefAppImpl();

            app.ScheduleMessagePumpWorkCallback = OnScheduleMessagePumpWork;
            app.CefProcessMessageReceived      += ScriptableObjectTests.HandleScriptableObjectTestMessage;
            try
            {
                UIContext = new WindowsFormsSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(UIContext);

                app.Initialize(Path.Combine(cefPath, "Release"), settings);

                if (externalMessagePump)
                {
                    messagePump = new System.Threading.Timer(_ => UIContext.Post(_ => CefApi.DoMessageLoopWork(), null), null, messagePumpDelay, messagePumpDelay);
                }

                Application.Run(new MainForm());

                using (var ev = new ManualResetEvent(false))
                {
                    app.SignalForShutdown(() => ev.Set());
                    ev.WaitOne();
                }
            }
            finally
            {
                messagePump?.Dispose();
                app.Shutdown();
                app.Dispose();
            }
        }
コード例 #45
0
        /// <summary>
        /// Turn automatic background repairs off and log the results.
        /// No counters are reset.
        /// </summary>
        public static void AutoOff()
        {
            Application.logMessageReceived -= LogMessageReceived;
            _backgroundTimer?.Dispose();

            SdtdConsole.Instance.LogAndOutput($"Automatic background {(PersistentData.Instance.RepairSimulate ? "scan (without repair)" : "repair")}" +
                                              $" for server problems {PersistentData.Instance.RepairTasks} turned OFF.");
            SdtdConsole.Instance.Output($"Report: {PersistentData.Instance.RepairCounter} problem{(PersistentData.Instance.RepairCounter == 1 ? " was" : "s were")} " +
                                        $"{(PersistentData.Instance.RepairSimulate ? "identified" : "repaired")} since it was turned on.");
        }
コード例 #46
0
ファイル: Program.cs プロジェクト: ChegnduJackli/Projects
        private static void ThreadingTimer()
        {
            var t1 = new System.Threading.Timer(
               TimeAction, null, TimeSpan.FromSeconds(2),
               TimeSpan.FromSeconds(3));

            Thread.Sleep(15000);

            t1.Dispose();
        }
コード例 #47
0
        public void Run()
        {
            System.Threading.Timer t = new System.Threading.Timer(new TimerCallback(timer_elapsed));
            Console.WriteLine("Starting timer at: ");
            Console.WriteLine(DateTime.Now);
            t.Change(1000, 1000);

            Thread.Sleep(5000);
            t.Dispose();
        }
コード例 #48
0
        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            _timer?.Dispose();
            Player?.StopPlayback();
            Player?.Dispose();
            Player = null;

            (Owner as MainForm)?.SetSecondForm(null);
        }
コード例 #49
0
        private void StartPing()
        {
            TestAllTimer?.Dispose();
            TestAllTimer      = new Timer(StartCore, null, 0, interval);
            Start_Button.Text = I18N.GetString(@"Stop");

            if (Dpi > 1.0)
            {
                Start_Button.ImageScaling = ToolStripItemImageScaling.None;
                Start_Button.Image        = Util.Util.ResizeImage(Resources.Stop, DpiPicSize);
            }
            else
            {
                Start_Button.Image        = Resources.Stop;
                Start_Button.ImageScaling = ToolStripItemImageScaling.SizeToFit;
            }

            StartStop_MenuItem.Text = I18N.GetString(@"Stop");
        }
コード例 #50
0
        private void SleepSetForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.notifyIcon1.BalloonTipText  = "Уведомление";
            this.notifyIcon1.BalloonTipTitle = $"Таймер выключения остановлен";
            this.notifyIcon1.BalloonTipIcon  = ToolTipIcon.Info;

            this.notifyIcon1.ShowBalloonTip(3000);

            prepareTimer?.Dispose();
        }
コード例 #51
0
 public void Dispose()
 {
     _settings.SettingUpdated -= OnSettingsSettingUpdated;
     lock (_lockingObject)
     {
         timerDisposed.Set();
         _timer?.Dispose();
         _memoryListener?.Dispose();
     }
 }
コード例 #52
0
        public void Dispose()
        {
            _songStatusWatcher?.Dispose();
            if (_backgroundChangeTracker != null && _backgroundChangeTracker.IsCompleted)
            {
                _backgroundChangeWorkerTokenSource.Cancel();
            }

            _backgroundChangeWorkerTokenSource.Dispose();
        }
コード例 #53
0
        private static void WaitOnTimer(TimeSpan dueTime, TimeSpan timeout)
        {
            var autoResetEvent = new AutoResetEvent(false);

            var timer = new Timer(state => autoResetEvent.Set(), null, dueTime, timeout);

            autoResetEvent.WaitOne(timeout);

            timer.Dispose();
        }
コード例 #54
0
 public void Dispose()
 {
     _connection?.Dispose();
     foreach (var channel in _threadChannels?.Values ?? Enumerable.Empty <IModel>())
     {
         channel?.Dispose();
     }
     _threadChannels?.Dispose();
     _closeTimer?.Dispose();
     _threadChannels = null;
 }
コード例 #55
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                components?.Dispose();
                components = null;

                _hideTimer?.Dispose();
                _hideTimer = null;
            }
            base.Dispose(disposing);
        }
コード例 #56
0
 private void Dispose(bool disposing)
 {
     if (disposed)
     {
         return;
     }
     if (disposing)
     {
         timer?.Dispose();
         serialPort?.Dispose();
     }
     disposed = true;
 }
コード例 #57
0
ファイル: MainWindow.cs プロジェクト: Narinyir/open3mod
        // http://stackoverflow.com/questions/2565166
        public static void DelayExecution(TimeSpan delay, Action action)
        {
            SynchronizationContext context = SynchronizationContext.Current;

            System.Threading.Timer timer = null;
            timer = new System.Threading.Timer(
                (_) => {
                if (timer != null)
                {
                    timer.Dispose();
                }
                context.Post(__ => action(), null);
            }, null, delay, TimeSpan.FromMilliseconds(-1));
        }
コード例 #58
0
 private void button5_Click(object sender, EventArgs e)
 {
     // 定时同步
     if (button5.Text == "定时同步")
     {
         timer        = new System.Threading.Timer(new TimerCallback(RedisCopy), null, 1000, int.Parse(textBox7.Text));
         button5.Text = "关闭同步";
     }
     else
     {
         timer?.Dispose( );
         button5.Text = "定时同步";
     }
 }
コード例 #59
0
        /// <summary>
        /// Raised by the <see cref="MeasurementTimer"/>. Collects data from board.
        /// </summary>
        private void OnMeasurementTimerTick(object state)
        {
            try {
                if (running)
                {
                    double time       = KeeperOfTime.ElapsedMilliseconds;
                    var    analogPins = Configuration.AnalogPins.Where(o => ((time % o.Interval) <= 10)).ToArray();
                    if (analogPins.Length > 0)
                    {
                        var query = analogPins.Select(o => o.Number).ToArray();
                        var vals  = ArduinoController.ReadAnalogPin(query);

                        var now = DateTime.Now;

                        for (int i = 0; i < analogPins.Length; i++)
                        {
                            lock (analogPins) {
                                analogPins [i].Value = new DateTimeValue(vals [i], now);
                            }
                        }

                        var analogPinValues      = analogPins.Select(o => o.Value.Value).ToList <double> ();
                        var analogPinValuesNames = analogPins.ToList().Select(o => o.DisplayName).ToList();

                        var MeComValues = Configuration.MeasurementCombinations
                                          .Where(o => !double.IsNaN(o.Value.Value))
                                          .Select(o => o.Value.Value)
                                          .ToList <double> ();
                        var MeComValuesNames = Configuration.MeasurementCombinations
                                               .Where(o => !double.IsNaN(o.Value.Value))
                                               .Select(o => o.DisplayName)
                                               .ToList();

                        var names = analogPinValuesNames;
                        names.AddRange(MeComValuesNames);
                        var values = analogPinValues;
                        values.AddRange(MeComValues);

                        MeasurementCSVLogger.Log(names, values);
                    }
                }
                else
                {
                    System.Threading.Timer t = (System.Threading.Timer)state;
                    t.Dispose();
                }
            } catch (Exception e) {
                ConLogger.Log(e.ToString(), LogLevel.ERROR);
            }
        }
コード例 #60
0
ファイル: DynamicElement.cs プロジェクト: leewoody/hobd
 private void ClickedTimer(object state)
 {
     if (clickTimer != null)
     {
         clickTimer.Dispose();
         clickTimer = null;
     }
     try{ //TODO!!!!
         if (!parent.IsDisposed)
         {
             parent.Invoke(new Action(parent.Invalidate));
         }
     }catch (Exception) {}
 }