• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# System.TimeSpan类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: XNAAsyncDispatcher

 public XNAAsyncDispatcher(TimeSpan dispatchInterval)
 {
     FrameworkDispatcher.Update();
     this._frameworkDispatcherTimer = new DispatcherTimer();
     this._frameworkDispatcherTimer.Tick += new EventHandler(frameworkDispatcherTimer_Tick);
     this._frameworkDispatcherTimer.Interval = dispatchInterval;
 }
开发者ID:jasonkuster,项目名称:MetroLooper,代码行数:7,代码来源:XNAAsyncDispatcher.cs


示例17: WatchFile

        /// <summary>
        /// A simpler alternative to the irritatingly useless FileSystemWatcher
        /// </summary>
        /// <param name="file">The file to monitor</param>
        /// <param name="refreshPeriod">The refresh period.</param>
        /// <param name="scheduler">The scheduler.</param>
        /// <returns></returns>
        public static IObservable<FileNotification> WatchFile(this FileInfo file, TimeSpan? refreshPeriod = null,
            IScheduler scheduler = null)
        {
           return Observable.Create<FileNotification>(observer =>
            {
                var refresh = refreshPeriod ?? TimeSpan.FromMilliseconds(250);
                scheduler = scheduler ?? Scheduler.Default;

                FileNotification notification = null;
                return scheduler.ScheduleRecurringAction(refresh, () =>
                {
                    try
                    {
                        notification = notification == null
                            ? new FileNotification(file)
                            : new FileNotification(notification);

                        observer.OnNext(notification);
                    }
                    catch (Exception ex)
                    {
                        notification = new FileNotification(file, ex);
                        observer.OnNext(notification);
                    }
                });

            }).DistinctUntilChanged();
        }
开发者ID:ItsJustSean,项目名称:TailBlazer,代码行数:35,代码来源:FileInfoEx.cs


示例18: Update

        public override void Update()
        {
            time -= GameGlobals.gameTime.ElapsedGameTime;

            if (time < TimeSpan.Zero)
                ScreenManager.CurrentScreen = destination;
        }
开发者ID:xennome,项目名称:FarmDead,代码行数:7,代码来源:Transition.cs


示例19: CreateConnectingTcpConnection

        public static ITcpConnection CreateConnectingTcpConnection(Guid connectionId, 
                                                                   IPEndPoint remoteEndPoint, 
                                                                   TcpClientConnector connector, 
                                                                   TimeSpan connectionTimeout,
                                                                   Action<ITcpConnection> onConnectionEstablished, 
                                                                   Action<ITcpConnection, SocketError> onConnectionFailed,
                                                                   bool verbose)
        {
            var connection = new TcpConnectionLockless(connectionId, remoteEndPoint, verbose);
// ReSharper disable ImplicitlyCapturedClosure
            connector.InitConnect(remoteEndPoint,
                                  (_, socket) =>
                                  {
                                      if (connection.InitSocket(socket))
                                      {
                                          if (onConnectionEstablished != null)
                                              onConnectionEstablished(connection);
                                          connection.StartReceive();
                                          connection.TrySend();
                                      }
                                  },
                                  (_, socketError) =>
                                  {
                                      if (onConnectionFailed != null)
                                          onConnectionFailed(connection, socketError);
                                  }, connection, connectionTimeout);
// ReSharper restore ImplicitlyCapturedClosure
            return connection;
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:29,代码来源:TcpConnectionLockless.cs


示例20: Configuration

 static Configuration()
 {
     AnnounceDir = ConfigurationSettings.AppSettings["AnnounceDir"].ToString();
     IconDir = ConfigurationSettings.AppSettings["IconDir"].ToString();
     AudioDir = "";
     AnnouncementMaxDuration = new TimeSpan(0, 20, 0);
 }
开发者ID:bashocz,项目名称:Empemont,代码行数:7,代码来源:Configuration.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# System.TimeZone类代码示例发布时间:2022-05-26
下一篇:
C# System.Thread类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap