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


C# Timer.Change方法代码示例

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


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

示例1: TimerTest0

        public MFTestResults TimerTest0()
        {
            MFTestResults result = MFTestResults.Pass;
            try
            {
                timerEvent.Reset();
                /// Save the current time shifted by 5 hours.
                
                timerTime = DateTime.UtcNow - utcTimeShiftAmount;
                using (Timer t = new Timer(new TimerCallback(TimerCallback), null, new TimeSpan(0, 0, 30), new TimeSpan(-TimeSpan.TicksPerMillisecond)))
                {
                    /// We shift the utc back by 5 hours.
                    TimeService.SetUtcTime(timerTime.Ticks); 
                    
                    /// timer should still fire after 30 seconds even though absolute time has been manipulated.
                    if (!timerEvent.WaitOne(2 * 60 * 1000, false))
                    {
                        result = MFTestResults.Fail;
                    }

                    /// Reset the changes.
                    TimeService.SetUtcTime((DateTime.UtcNow + utcTimeShiftAmount).Ticks);

                    t.Change(-1, -1);
                }
            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected exception", ex);
                result = MFTestResults.Fail;
            }

            return result;
        }
开发者ID:trfiladelfo,项目名称:MicroFrameworkSDK-Mono,代码行数:34,代码来源:ServiceTests.cs

示例2: Timer_Change_UInt32_Int64_AfterDispose_Throws

 public void Timer_Change_UInt32_Int64_AfterDispose_Throws()
 {
     var t = new Timer(EmptyTimerTarget);
     t.Dispose();
     Assert.Throws<ObjectDisposedException>(() => t.Change(0u, 0u));
     Assert.Throws<ObjectDisposedException>(() => t.Change(0L, 0L));
 }
开发者ID:dotnet,项目名称:corefx,代码行数:7,代码来源:TimerChangeTests.netstandard1.7.cs

示例3: BackupSetViewModel

        public BackupSetViewModel(IBackupSet backupSet, IUIVisualizerService uiVisualizerService)
        {
            Argument.IsNotNull(() => backupSet);
            Argument.IsNotNull(() => uiVisualizerService);
            BackupSet = backupSet;
            _uiVisualizerService = uiVisualizerService;
            _timer = new Timer(new TimerCallback((o)=>
            {
                RefreshLog();
            }), null, Timeout.Infinite, Timeout.Infinite);

            UpdateScheduleStatus();            
         
            BrowseSourceCommand = new Command(() => SourceDirectory = SetDirectory(SourceDirectory, "Select Source Directory"));
            BrowseDestinationCommand = new Command(() => DestinationDirectory = SetDirectory(DestinationDirectory, "Select Destination Directory"));
            ExcludeDirectoriesCommand = new Command(OnExcludeDirectoriesExecute, ()=>!String.IsNullOrEmpty(SourceDirectory));
            RunBackupCommand = new Command(() => 
                {
                    if(BackupSet.DestinationType == BackupDestinationType.ExternalDrive)
                    {
                        var typeFactory = this.GetTypeFactory();
                        var driveSelectionViewModel = typeFactory.CreateInstanceWithParametersAndAutoCompletion<DriveSelectionViewModel>();
                        driveSelectionViewModel.SetDefaultDrive(DestinationDirectory.Substring(0, 1));
                        if(_uiVisualizerService.ShowDialog(driveSelectionViewModel) == true )
                        {
                            UpdateDestinationDriveLetter(driveSelectionViewModel.SelectedDrive.Name);
                        }
                        else
                        {
                            return;
                        }
                        
                    }
                    _timer.Change(1000, 1000);
                    BackupSet.RunBackup();
                }  
                , () => CanRunBackup);

            CancelBackupCommand = new Command(() =>
                {
                    _timer.Change(Timeout.Infinite, Timeout.Infinite);
                    BackupSet.CancelBackup();
                }
                , () => CanCancelBackup);

            EditBackupSetCommand = new RelayCommand((o)=>
            {
                StateService.RequestBackupSetEdit((string)o);
            }
            ,(o) =>   ProcessingStatus == BackupProcessingStatus.NotStarted ||
                ProcessingStatus == BackupProcessingStatus.Cancelled ||
                ProcessingStatus == BackupProcessingStatus.Finished);

            FinishEditingBackupSetCommand = new RelayCommand((o) =>
            {
                StateService.RequestBackupSetEdit((string)o);
            });           
            
            BackupSet.PropertyChanged += BackupSetPropertyChanged;            
        }
开发者ID:simon-knox,项目名称:SafeAndSound2014,代码行数:60,代码来源:BackupSetViewModel.cs

示例4: SendData

        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.");
        }
开发者ID:matt-softlogic,项目名称:samples,代码行数:58,代码来源:Program.cs

示例5: HandleMasterPersistence

        /// <summary>
        /// Handle the scenario when PersistTo == 1
        /// </summary>
        public IObserveOperationResult HandleMasterPersistence(ICouchbaseServerPool pool)
        {
            try
            {
                var commandConfig = setupObserveOperation(pool);
                var node = commandConfig.Item2[0] as CouchbaseNode;
                IObserveOperationResult result = new ObserveOperationResult();

                do
                {
                    var are = new AutoResetEvent(false);
                    var timer = new Timer(state =>
                    {
                        result = node.ExecuteObserveOperation(commandConfig.Item3);

                        if (log.IsDebugEnabled) log.Debug("Node: " + node.EndPoint + ", Result: " + result.KeyState + ", Cas: " + result.Cas + ", Key: " + _settings.Key);

                        if (result.Success && result.Cas != _settings.Cas && result.Cas > 0)
                        {
                            result.Fail(ObserveOperationConstants.MESSAGE_MODIFIED);
                            are.Set();
                        }
                        else if (result.KeyState == ObserveKeyState.FoundPersisted)
                        {
                            result.Pass();
                            are.Set();
                        }

                    }, are, 0, 500);

                    if (!are.WaitOne(_settings.Timeout))
                    {
                        timer.Change(-1, -1);
                        result.Fail(ObserveOperationConstants.MESSAGE_TIMEOUT, new TimeoutException());
                        break;
                    }

                    timer.Change(-1, -1);

                } while (result.Message == string.Empty && result.KeyState != ObserveKeyState.FoundPersisted);

                return result;
            }
            catch (Exception ex)
            {
                return new ObserveOperationResult { Success = false, Exception = ex };
            }
        }
开发者ID:e-travel,项目名称:couchbase-net-client,代码行数:51,代码来源:ObserveHandler.cs

示例6: Main

        static void Main(string[] args)
        {
            var bus = RabbitHutch.CreateBus("host=localhost");
            var count = 0;

            var timer = new Timer(x =>
            {
                try
                {
                    using (var publishChannel = bus.OpenPublishChannel())
                    {
                        publishChannel.Request<TestRequestMessage, TestResponseMessage>(
                            new TestRequestMessage { Text = string.Format("Hello from client number: {0}! ", count++) },
                            ResponseHandler);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Exception thrown by Publish: {0}", exception.Message);
                }
            }, null, 1000, 1000);

            Console.Out.WriteLine("Timer running, ctrl-C to end");

            Console.CancelKeyPress += (source, cancelKeyPressArgs) =>
            {
                Console.Out.WriteLine("Shutting down");

                timer.Dispose();
                bus.Dispose();
                Console.WriteLine("Shut down complete");
            };

            var running = true;
            while (true)
            {
                Console.ReadKey();
                if (running)
                {
                    timer.Change(Timeout.Infinite, Timeout.Infinite);
                }
                else
                {
                    timer.Change(1000, 1000);
                }
                running = !running;
            }
        }
开发者ID:IanYates,项目名称:EasyNetQ,代码行数:48,代码来源:Program.cs

示例7: AuthQueue

		static AuthQueue()
		{
			s_queuedClients = new LockfreeQueue<IRealmClient>();
			s_checkTimer = new Timer(ProcessQueuedClients);

			s_checkTimer.Change(TimeSpan.FromSeconds(15.0), TimeSpan.FromSeconds(15.0));
		}
开发者ID:pallmall,项目名称:WCell,代码行数:7,代码来源:AuthQueue.cs

示例8: MainVM

        private MainVM()
        {
            #if DEBUG
            LoggerFactory.SetLoggerLevel(LoggerLevel.Trance);
            #else
            LoggerFactory.SetLoggerInstance(typeof(MyLogger));
            #endif

            _udpClient = new UdpClient();
            _udpClient.RequestAction = ServerRequest;

            _autoTimer = new Timer(AtuoTimerCallback, null, Timeout.Infinite, Timeout.Infinite);

            _tcpClient = new TcpClient();
            _tcpClient.OpenedAction = ServerOpened;
            _tcpClient.ClosedAction = ServerClosed;
            _tcpClient.FaultAction = ServerFaulted;
            _tcpClient.ReceivedAction = Received;

            if (SettingVM.Instance.AutoAddress)
            {
                _udpClient.Start();
            }
            else
            {
                _autoTimer.Change(Common.AutoConnectInterval, Common.AutoConnectInterval);
            }
        }
开发者ID:Jitlee,项目名称:RemoteShutdown,代码行数:28,代码来源:MainVM.cs

示例9: Start

        public void Start(TimeSpan timerInterval, bool triggerAtStart = false,
            object state = null)
        {
            Stop();
            _timer = new System.Threading.Timer(Timer_Elapsed, state,
                System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);

            if (triggerAtStart)
            {
                _timer.Change(TimeSpan.FromTicks(0), timerInterval);
            }
            else
            {
                _timer.Change(timerInterval, timerInterval);
            }
        }
开发者ID:Dev01FC,项目名称:CnC-SC,代码行数:16,代码来源:TimerHelper.cs

示例10: PythonInterpreterFactoryWithDatabase

        public PythonInterpreterFactoryWithDatabase(
            Guid id,
            string description,
            InterpreterConfiguration config,
            bool watchLibraryForChanges
        ) {
            _description = description;
            _id = id;
            _config = config;

            if (watchLibraryForChanges && Directory.Exists(_config.LibraryPath)) {
                _refreshIsCurrentTrigger = new Timer(RefreshIsCurrentTimer_Elapsed);

                _libWatcher = CreateLibraryWatcher();

                _isCheckingDatabase = true;
                _refreshIsCurrentTrigger.Change(1000, Timeout.Infinite);

                _verWatcher = CreateDatabaseVerWatcher();
                _verDirWatcher = CreateDatabaseDirectoryWatcher();
            }

            // Assume the database is valid if the directory exists, then switch
            // to invalid after we've checked.
            _isValid = Directory.Exists(DatabasePath);
        }
开发者ID:wenh123,项目名称:PTVS,代码行数:26,代码来源:PythonInterpreterFactoryWithDatabase.cs

示例11: GetNetworkBssList

        private async Task<IEnumerable<WlanInterop.WlanBssEntry>> GetNetworkBssList(Guid interfaceGuid)
        {
            WlanInterop.WlanScan(this.clientHandle, interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            // Ideally, wait for a callback, but there were some COM timing issues with that.
            // So just wait.
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            Timer timer = null;
            timer = new Timer(s =>
            {
                timer.Dispose();
                tcs.SetResult(true);
            }, null, -1, -1);
            timer.Change(5000, -1);
            await tcs.Task;

            IntPtr wlanBssList = IntPtr.Zero;
            List<WlanInterop.WlanBssEntry> result;
            try
            {
                WlanInterop.WlanGetNetworkBssList(this.clientHandle, interfaceGuid, IntPtr.Zero, WlanInterop.Dot11BssType.Any, false, IntPtr.Zero, out wlanBssList);
                result = this.GetBssListFromPointer(wlanBssList);
            }
            finally
            {
                WlanInterop.WlanFreeMemory(wlanBssList);
            }
            return result;
        }
开发者ID:jcookems,项目名称:freezing-ninja,代码行数:28,代码来源:WlanClient.cs

示例12: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var cts = new CancellationTokenSource();
            var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
            var linkedToken = linkedTokenSource.Token;
            var timer = new Timer(s_timerCallback, cts, -1, -1);

            request.RegisterForDispose(timer);
            request.RegisterForDispose(cts);
            request.RegisterForDispose(linkedTokenSource);

            timer.Change(_milliseconds, -1);

            return base.SendAsync(request, linkedToken).ContinueWith(task => {

                if (task.Status == TaskStatus.Canceled) {

                    return request.CreateResponse(HttpStatusCode.RequestTimeout);
                }

                //TODO: Handle faulted task as well

                return task.Result;

            }, TaskContinuationOptions.ExecuteSynchronously);
        }
开发者ID:serdarb,项目名称:WebAPIDoodle,代码行数:26,代码来源:TimeoutHandler.cs

示例13: MainWindow

        public MainWindow()
        {
            InitializeComponent();

            if (File.Exists(ConfigurationFile))
            {
                try
                {
                    _configuration = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText(ConfigurationFile));
                }
                catch (Exception)
                {
                    Debug.WriteLine("Cannot load configuration file {0}", ConfigurationFile);
                }
            }

            if (_configuration == null)
            {
                _configuration = Configuration.Default;
                File.WriteAllText(ConfigurationFile, JsonConvert.SerializeObject(_configuration, new JsonSerializerSettings() { Formatting = Formatting.Indented }));
            }

            DataContext = this;

            _timer = new Timer(ShowBalloon);
            _timer.Change(TimeSpan.FromMinutes(_configuration.StartAfterMinutes),
                TimeSpan.FromHours(_configuration.AfterHours).Add(TimeSpan.FromMinutes(_configuration.AfterMinutes)));
        }
开发者ID:bshishov,项目名称:StressStat,代码行数:28,代码来源:MainWindow.xaml.cs

示例14: After

 public static Channel<DateTime> After(TimeSpan after)
 {
     var ch = new Channel<DateTime>(1);
     var t = new Timer(state => { ch.TrySend(DateTime.Now); ch.Close(); });
     t.Change(after, TimeSpan.FromMilliseconds(-1));
     return ch;
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:7,代码来源:Time.cs

示例15: Timer_Change_NegativeInt_Period_Throws

 public void Timer_Change_NegativeInt_Period_Throws()
 {
     using (var t = new Timer(new TimerCallback(EmptyTimerTarget), null, 1, 1))
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => t.Change(1 /* not relevant */, -2));
     }
 }
开发者ID:jmhardison,项目名称:corefx,代码行数:7,代码来源:TimerChangeTests.cs


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