本文整理汇总了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;
}
示例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;
}
}
}
示例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;
}
示例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();
}
}
示例5: Update
public override void Update(TimeSpan elapsed)
{
if (Reflected)
Move();
Reflected = false;
base.Update(elapsed);
}
示例6: CommandMessage
public CommandMessage(string cmdText, TimeSpan duration, string type, string connectionGUID)
{
CommandText = cmdText;
Duration = duration;
Type = type;
ConnectionGUID = connectionGUID;
}
示例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);
}
示例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;
}
}
示例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();
}
示例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;
}
示例11: Enter
public void Enter(TimeSpan timeout)
{
if (!this.TryEnter(timeout))
{
throw Fx.Exception.AsError(CreateEnterTimedOutException(timeout));
}
}
示例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;
}
示例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);
}
示例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);
}
示例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();
}