当前位置: 首页>>代码示例>>C#>>正文


C# Timer.Dispose方法代码示例

本文整理汇总了C#中System.Threading.Timer.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Timer.Dispose方法的具体用法?C# Timer.Dispose怎么用?C# Timer.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.Timer的用法示例。


在下文中一共展示了Timer.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Worker

        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();
        }
开发者ID:risedphantom,项目名称:MassMailer,代码行数:25,代码来源:MailWorker.cs

示例2: DisposeTimer

 public static void DisposeTimer(Timer timer)
 {
     Check.Require(timer, "timer");
     var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
     timer.Dispose(waitHandle);
     waitHandle.WaitOne(1000);
 }
开发者ID:HNeukermans,项目名称:Hallo,代码行数:7,代码来源:SipUtil.cs

示例3: SocketListenerThreadStart

        //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;
        }
开发者ID:thisthat,项目名称:SpotifyController,代码行数:30,代码来源:TCPSocketListener.cs

示例4: ShowRace

        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);
        }
开发者ID:squimmy,项目名称:SnailRace,代码行数:26,代码来源:RaceViewer.cs

示例5: Main

        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.");
        }
开发者ID:JeffESchmitz,项目名称:Console.Examples,代码行数:25,代码来源:Program.cs

示例6: Run

        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();
        }
开发者ID:laurikoobas,项目名称:Azure,代码行数:28,代码来源:WorkerRole.cs

示例7: Method_2

        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);
            }
        }
开发者ID:RoykoSerhiy,项目名称:visualStudio_projects,代码行数:34,代码来源:Program.cs

示例8: Work

        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);
        }
开发者ID:kalantyr,项目名称:Parallel,代码行数:32,代码来源:CharactersController.cs

示例9: GetRequestTime

        /// <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;
        }
开发者ID:CoffeeNova,项目名称:bfbalance,代码行数:41,代码来源:ByflyTools.cs

示例10: ImageLoader

 static ImageLoader()
 {
     _expirationTimer = new Timer(_ => RemoveExpiredCaches(), null,
         TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
     App.ApplicationFinalize += () => _expirationTimer.Dispose();
     StartDecodeThread();
 }
开发者ID:Kei-Nanigashi,项目名称:StarryEyes,代码行数:7,代码来源:ImageLoader.cs

示例11: ThreadingTimer

 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();
 }
开发者ID:ChrisChen3121,项目名称:MySourceLib,代码行数:7,代码来源:Program.cs

示例12: Main

 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();
 }
开发者ID:RoykoSerhiy,项目名称:visualStudio_projects,代码行数:7,代码来源:Program.cs

示例13: Main

        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);
        }
开发者ID:JohnEffo,项目名称:EasyNetQ,代码行数:26,代码来源:Program.cs

示例14: AddTask

        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);
        }
开发者ID:eranbetzalel,项目名称:SimpleBackup,代码行数:25,代码来源:Scheduler.cs

示例15: StartNewDelayed

        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;
        }
开发者ID:geffzhang,项目名称:Foundatio,代码行数:34,代码来源:TaskFactoryExtensions.cs


注:本文中的System.Threading.Timer.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。