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


C# System.TimeSpan类代码示例

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


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

示例1: IdleExpiration

        /// <summary>
		/// Constructor
		/// </summary>
		/// <param name="idleTTL">the idle time to live value</param>
		public IdleExpiration(TimeSpan idleTTL)
		{			
            this.SetBit(IS_VARIANT);
			_idleTimeToLive = (int)idleTTL.TotalSeconds;
            _lastTimeStamp = AppUtil.DiffSeconds(DateTime.Now);
            _hintType = ExpirationHintType.IdleExpiration;
		}
开发者ID:christrotter,项目名称:NCache,代码行数:11,代码来源:IdleExpiration.cs

示例2: Update

        protected override void Update(TimeSpan gameTime)
        {
            if (this.CurrentState == States.Menu)
            {
                Input input = WaveServices.Input;

                if ((input.TouchPanelState.IsConnected && input.TouchPanelState.Count > 0) ||
                    (input.KeyboardState.IsConnected &&
                    (input.KeyboardState.Space == ButtonState.Pressed ||
                     input.KeyboardState.A == ButtonState.Pressed ||
                     input.KeyboardState.S == ButtonState.Pressed ||
                     input.KeyboardState.D == ButtonState.Pressed ||
                     input.KeyboardState.W == ButtonState.Pressed ||
                     input.KeyboardState.Up == ButtonState.Pressed ||
                     input.KeyboardState.Down == ButtonState.Pressed ||
                     input.KeyboardState.Left == ButtonState.Pressed ||
                     input.KeyboardState.Right == ButtonState.Pressed)))
                {
                    this.CurrentState = States.GamePlay;
                }
            }
            else if (this.CurrentState == States.GamePlay)
            {
                if (this.player.Life <= 0)
                {
                    this.CurrentState = States.GameOver;
                }
            }
        }
开发者ID:gsemerdjiev,项目名称:QuickStarters,代码行数:29,代码来源:GamePlayManager.cs

示例3: Update

        protected override void Update(TimeSpan gameTime)
        {
            input = WaveServices.Input;

            if (input.KeyboardState.IsConnected)
            {
                keyboardState = input.KeyboardState;

                if (keyboardState.W == ButtonState.Pressed)
                {
                    MoveCamera(ref forward);
                }
                if (keyboardState.S == ButtonState.Pressed)
                {
                    MoveCamera(ref back);
                }
                if (keyboardState.A == ButtonState.Pressed)
                {
                    MoveCamera(ref left);
                }
                if (keyboardState.D == ButtonState.Pressed)
                {
                    MoveCamera(ref right);
                }
            }
            var rotationMatrix = (Matrix.CreateRotationX(MathHelper.ToRadians(45.0f)) * Matrix.CreateRotationY(MathHelper.ToRadians(30.0f)));
            Vector3 transformedReference = Vector3.Transform(Vector3.Down, rotationMatrix);
            Vector3 cameraLookat = Camera.Position + transformedReference;
            var width = WaveServices.Platform.ScreenWidth / 24;
            var height = WaveServices.Platform.ScreenHeight / 24;

            //camera.Projection = Matrix.CreateOrthographic(width, height, camera.NearPlane, camera.FarPlane);
            Camera.LookAt = cameraLookat;
        }
开发者ID:123asd123A,项目名称:Samples,代码行数:34,代码来源:IsometricCameraBehavior.cs

示例4: Initialize

        /// <summary>
        /// Initializes the service.
        /// </summary>
        /// <param name="pollingInterval">The polling interval. If <c>default(TimeSpan)</c>, no polling will be enabled.</param>
        /// <returns>Task.</returns>
        /// <remarks>Note that this method is optional but will start the service. If this method is not called, the service will be initialized
        /// in the <see cref="ValidateLicense" /> method.</remarks>
        public virtual void Initialize(TimeSpan pollingInterval = default(TimeSpan))
        {
            CreateLicenseListeningSockets();

            if (_pollingTimer.Enabled)
            {
                Log.Debug("Stopping network polling");

                _pollingTimer.Stop();
                _pollingTimer.Elapsed -= OnPollingTimerElapsed;
            }

            if (pollingInterval != default(TimeSpan))
            {
                if (pollingInterval < SearchTimeout)
                {
                    Log.Warning("Polling interval is smaller than SearchTimeout, defaulting to SearchTimeout + 5 seconds");

                    pollingInterval = SearchTimeout.Add(TimeSpan.FromSeconds(5));
                }

                Log.Debug("Starting network polling with an interval of '{0}'", pollingInterval);

                _pollingTimer.Interval = pollingInterval.TotalMilliseconds;
                _pollingTimer.Elapsed += OnPollingTimerElapsed;
                _pollingTimer.Start();
            }
        }
开发者ID:WildGums,项目名称:Orc.LicenseManager,代码行数:35,代码来源:NetworkLicenseService.cs

示例5: Update

 public override void Update(TimeSpan elapsed)
 {
     if (Reflected)
         Move();
     Reflected = false;
     base.Update(elapsed);
 }
开发者ID:RavingRabbit,项目名称:Labs,代码行数:7,代码来源:HardBall.cs

示例6: CommandMessage

 public CommandMessage(string cmdText, TimeSpan duration, string type, string connectionGUID)
 {
     CommandText = cmdText;
     Duration = duration;
     Type = type;
     ConnectionGUID = connectionGUID;
 }
开发者ID:pietervp,项目名称:DbProfiler,代码行数:7,代码来源:CommandMessage.cs

示例7: AwaitCondition

 /// <summary>
 /// <para>Await until the given condition evaluates to <c>true</c> or the timeout
 /// expires, whichever comes first.</para>
 /// <para>If no timeout is given, take it from the innermost enclosing `within`
 /// block (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". 
 /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor 
 /// specified in config value "akka.test.timefactor"..</para>
 /// <para>A call to <paramref name="conditionIsFulfilled"/> is done immediately, then the threads sleep
 /// for about a tenth of the timeout value, before it checks the condition again. This is repeated until
 /// timeout or the condition evaluates to <c>true</c>. To specify another interval, use the overload
 /// <see cref="AwaitCondition(System.Func{bool},System.Nullable{System.TimeSpan},System.Nullable{System.TimeSpan},string)"/>
 /// </para>
 /// </summary>
 /// <param name="conditionIsFulfilled">The condition that must be fulfilled within the duration.</param>
 /// <param name="max">The maximum duration. If undefined, uses the remaining time 
 /// (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". 
 /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor 
 /// specified in config value "akka.test.timefactor".</param>
 /// <param name="message">The message used if the timeout expires.</param>
 public void AwaitCondition(Func<bool> conditionIsFulfilled, TimeSpan? max, string message)
 {
     var maxDur = RemainingOrDilated(max);
     var interval = new TimeSpan(maxDur.Ticks / 10);
     var logger = _testState.TestKitSettings.LogTestKitCalls ? _testState.Log : null;
     InternalAwaitCondition(conditionIsFulfilled, maxDur, interval, (format, args) => AssertionsFail(format, args, message), logger);
 }
开发者ID:Micha-kun,项目名称:akka.net,代码行数:26,代码来源:TestKitBase_AwaitConditions.cs

示例8: Exists

        public async Task<bool> Exists(string fileName, TimeSpan expiration)
        {
            try
            {
                var exists = true;

                var file = await _baseFolder.TryGetItemAsync(fileName.CleanCharacters());
                if (file != null)
                {
                    var createdAt = file.DateCreated;
                    var timeDiff = (DateTimeOffset.Now - createdAt);
                    if (timeDiff > expiration)
                        exists = false;

                    return exists;
                }
                else
                    return false;

            }
            catch (FileNotFoundException)
            {
                return false;
            }
        }
开发者ID:wuchangqi,项目名称:ifixit-microsoft,代码行数:25,代码来源:UiStorage.cs

示例9: Arrange

        protected void Arrange()
        {
            var random = new Random();
            _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
            _operationTimeout = TimeSpan.FromSeconds(30);
            _encoding = Encoding.UTF8;
            _disconnectedRegister = new List<EventArgs>();
            _errorOccurredRegister = new List<ExceptionEventArgs>();
            _channelDataEventArgs = new ChannelDataEventArgs(
                (uint)random.Next(0, int.MaxValue),
                new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelMock = new Mock<IChannelSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
            _channelMock.InSequence(_sequence).Setup(p => p.Open());
            _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);

            _subsystemSession = new SubsystemSessionStub(
                _sessionMock.Object,
                _subsystemName,
                _operationTimeout,
                _encoding);
            _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
            _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
            _subsystemSession.Connect();
        }
开发者ID:delfinof,项目名称:ssh.net,代码行数:29,代码来源:SubsystemSession_OnChannelDataReceived_Connected.cs

示例10: SplunkContext

 /// <summary>
 /// Creates an instance of the SplunkViaHttp context
 /// </summary>
 public SplunkContext(SplunkClient.Scheme scheme, string host, int port, string index, string username, string password, TimeSpan timeout, HttpMessageHandler handler, bool disposeHandler = true)
     : base(scheme, host, port, timeout, handler, disposeHandler)
 {
     Index = index;
     Username = username;
     Password = password;
 }
开发者ID:bry4ngh0st,项目名称:serilog-sinks-splunk,代码行数:10,代码来源:SplunkContext.cs

示例11: Enter

 public void Enter(TimeSpan timeout)
 {
     if (!this.TryEnter(timeout))
     {
         throw Fx.Exception.AsError(CreateEnterTimedOutException(timeout));
     }
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:7,代码来源:ThreadNeutralSemaphore.cs

示例12: LinearSmoothMove

        public static void LinearSmoothMove(Point newPosition, TimeSpan duration)
        {
            Point start = Cursor.Position;

            var rnd = new Random();
            // Find the vector between start and newPosition
            double deltaX = newPosition.X - start.X;
            double deltaY = newPosition.Y - start.Y;

            // start a timer
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            double timeFraction = 0.0;

            do
            {
                var v = rnd.Next(0, 1000);
                Trace.WriteLine(stopwatch.Elapsed.Ticks + ", " + v + ", " + (double)(stopwatch.Elapsed.Ticks + v) / duration.Ticks);
                timeFraction = (double)(stopwatch.Elapsed.Ticks + v * 5) / duration.Ticks;
                if (timeFraction > 1.0)
                    timeFraction = 1.0;

                var addX = rnd.Next(0, 10);
                var addY = rnd.Next(0, 10);
                var curPoint = new Point(start.X + (int)(timeFraction * deltaX) + addX,
                                             start.Y + (int)(timeFraction * deltaY) + addY);
                Cursor.Position = curPoint;

                Thread.Sleep(20);
            } while (timeFraction < 1.0);

            Cursor.Position = newPosition;
        }
开发者ID:ramonliu,项目名称:poker-miranda,代码行数:34,代码来源:WinApi.cs

示例13: Game

        public Game(UserControl userControl, Canvas drawingCanvas, Canvas debugCanvas, TextBlock txtDebug)
        {
            //Initialize
            IsActive = true;
            IsFixedTimeStep = true;
            TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 16);
            Components = new List<DrawableGameComponent>();
            World = new World(new Vector2(0, 0));
            _gameTime = new GameTime();
            _gameTime.GameStartTime = DateTime.Now;
            _gameTime.FrameStartTime = DateTime.Now;
            _gameTime.ElapsedGameTime = TimeSpan.Zero;
            _gameTime.TotalGameTime = TimeSpan.Zero;

            //Setup Canvas
            DrawingCanvas = drawingCanvas;
            DebugCanvas = debugCanvas;
            TxtDebug = txtDebug;
            UserControl = userControl;

            //Setup GameLoop
            _gameLoop = new Storyboard();
            _gameLoop.Completed += GameLoop;
            _gameLoop.Duration = TargetElapsedTime;
            DrawingCanvas.Resources.Add("gameloop", _gameLoop);
        }
开发者ID:hilts-vaughan,项目名称:Farseer-Physics,代码行数:26,代码来源:Game.cs

示例14: GenerateComb

        /// <summary>
        /// Generate a new <see cref="Guid"/> using the comb algorithm.
        /// </summary>
        private Guid GenerateComb()
        {
            byte[] guidArray = Guid.NewGuid().ToByteArray();

            DateTime baseDate = new DateTime(1900, 1, 1);
            DateTime now = DateTime.Now;

            // Get the days and milliseconds which will be used to build the byte string
            TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);
            TimeSpan msecs = now.TimeOfDay;

            // Convert to a byte array
            // Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333
            byte[] daysArray = BitConverter.GetBytes(days.Days);
            byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));

            // Reverse the bytes to match SQL Servers ordering
            Array.Reverse(daysArray);
            Array.Reverse(msecsArray);

            // Copy the bytes into the guid
            Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
            Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);

            return new Guid(guidArray);
        }
开发者ID:pleb,项目名称:Chillow,代码行数:29,代码来源:ExistingIdOrGuidCombGenerator.cs

示例15: Update

        public void Update()
        {
            if (_deploysRemaining > 0 && _time.Minutes % 15 == 0 && _time.Seconds == 0)
            {
                _deploysRemaining--;
                //_trains.Add(new Bullet(_stations["Glenhuntly"].GetPlatform(1)));
                //_trains.Add(new Bullet(_stations["Windsor"].GetPlatform(1)));
                //_trains.Add(new Bullet(_stations["Hawthorn"].GetPlatform(1)));
                //_trains.Add(new Bullet(_stations["Jolimont"].GetPlatform(1)));
                for (int i = 0; i < 75; i++)
                {
                    Station station = _links[MathUtils.Rand(0, _links.Count - 1)].InStation;
                    Platform platform = station.GetPlatform(MathUtils.Rand(1, station.PlatformCount));
                    if (!platform.IsOccupied)
                    {
                        Train train = Train.Generate(platform);
                        platform.Occupy(train);
                        _trains.Add(train);
                    }
                }
            }

            _time = _time.Add(new TimeSpan(0, 0, 1));
            foreach (Train train in _trains)
                train.Update();
        }
开发者ID:LRih,项目名称:Train-Network-Simulator,代码行数:26,代码来源:TrainNetwork.cs


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