本文整理汇总了C#中System.TimeSpan.GetValueOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# TimeSpan.GetValueOrDefault方法的具体用法?C# TimeSpan.GetValueOrDefault怎么用?C# TimeSpan.GetValueOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.TimeSpan
的用法示例。
在下文中一共展示了TimeSpan.GetValueOrDefault方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DeadTime
public virtual DateTime DeadTime(int attempts, TimeSpan? timeoutFactor, TimeSpan? maxDeadTimeout)
{
var timeout = timeoutFactor.GetValueOrDefault(DefaultTimeout);
var maxTimeout = maxDeadTimeout.GetValueOrDefault(MaximumTimeout);
var milliSeconds = Math.Min(timeout.TotalMilliseconds * 2 * Math.Pow(2, attempts * 0.5 - 1), maxTimeout.TotalMilliseconds);
return Now().AddMilliseconds(milliSeconds);
}
示例2: OACommandExecuted
public OACommandExecuted(DateTime startTime, TimeSpan? duration, string eventName, string subEventText)
{
this.id = Guid.NewGuid();
this.EventName = eventName;
this.StartTime = startTime;
this.Duration = duration.GetValueOrDefault();
this.EventCategory = new TimelineCategoryItem("OpenAccess ORM", "#FF0F2B", "#FF0F2B");
this.EventSubText = subEventText;
}
示例3: WatchedFileChecker
public WatchedFileChecker(ReadedFileInfo fileInfo, TimeSpan? delay, CheckMode checkMode)
: base(fileInfo)
{
_delay = delay.GetValueOrDefault(TimeSpan.FromSeconds(5 * 60));
if (_delay <= TimeSpan.FromMilliseconds(1))
throw new ArgumentOutOfRangeException("delay should be greater of 1 ms");
_fileInfo = fileInfo;
_checkMode = checkMode;
_watcher = createWatch();
Task.Run(() => checkLoop()).ThrowUnhandledException("Error while file checking.");
}
示例4: CsvRequestLogger
public CsvRequestLogger(IVirtualFiles files = null, string requestLogsPattern = null, string errorLogsPattern = null, TimeSpan? appendEvery = null)
{
this.files = files ?? new FileSystemVirtualPathProvider(HostContext.AppHost, HostContext.Config.WebHostPhysicalPath);
this.requestLogsPattern = requestLogsPattern ?? "requestlogs/{year}-{month}/{year}-{month}-{day}.csv";
this.errorLogsPattern = errorLogsPattern ?? "requestlogs/{year}-{month}/{year}-{month}-{day}-errors.csv";
this.appendEverySecs = (int)appendEvery.GetValueOrDefault(TimeSpan.FromSeconds(1)).TotalSeconds;
var lastEntry = ReadLastEntry(GetLogFilePath(this.requestLogsPattern, DateTime.UtcNow));
if (lastEntry != null)
requestId = lastEntry.Id;
timer = new Timer(OnFlush, null, this.appendEverySecs, Timeout.Infinite);
}
示例5: AddFrame
/// <summary>
/// Adds a frame to this animation.
/// </summary>
/// <param name="img">The image to add</param>
/// <param name="x">The positioning x offset this image should be displayed at.</param>
/// <param name="y">The positioning y offset this image should be displayed at.</param>
public void AddFrame(Image img, int x = 0, int y = 0, TimeSpan? frameDelay = null)
{
using (var gifStream = new MemoryStream())
{
img.Save(gifStream, ImageFormat.Gif);
if (_isFirstImage) // Steal the global color table info
{
InitHeader(gifStream, img.Width, img.Height);
}
WriteGraphicControlBlock(gifStream, frameDelay.GetValueOrDefault(FrameDelay));
WriteImageBlock(gifStream, !_isFirstImage, x, y, img.Width, img.Height);
}
_isFirstImage = false;
}
示例6: AwaitAssert
/// <summary>
/// <para>Await until the given assertion does not throw an exception or the timeout
/// expires, whichever comes first. If the timeout expires the last exception
/// is thrown.</para>
/// <para>The action is called, and if it throws an exception the thread sleeps
/// the specified interval before retrying.</para>
/// <para>If no timeout is given, take it from the innermost enclosing `within`
/// block.</para>
/// <para>Note that the timeout is scaled using <see cref="Dilated" />,
/// which uses the configuration entry "akka.test.timefactor".</para>
/// </summary>
/// <param name="assertion">The action.</param>
/// <param name="duration">The timeout.</param>
/// <param name="interval">The interval to wait between executing the assertion.</param>
public void AwaitAssert(Action assertion, TimeSpan? duration=null, TimeSpan? interval=null)
{
var intervalValue = interval.GetValueOrDefault(TimeSpan.FromMilliseconds(800));
if(intervalValue == Timeout.InfiniteTimeSpan) intervalValue = TimeSpan.MaxValue;
intervalValue.EnsureIsPositiveFinite("interval");
var max = RemainingOrDilated(duration);
var stop = Now + max;
var t = max.Min(intervalValue);
while(true)
{
try
{
assertion();
return;
}
catch(Exception)
{
if(Now + t >= stop)
throw;
}
Thread.Sleep(t);
t = (stop - Now).Min(intervalValue);
}
}
示例7: Run
public void Run()
{
if(this.CurrentItemAmount != this.ItemsToLoad) {
int index = 0;
int currentIndex = 0;
TimeSpan? totalTime = null;
TimeSpan totalLoadingTime = new TimeSpan();
foreach(Card card in CardBase.Cards) {
foreach(KeyValuePair<Edition, EditionImage> pair in card.EditionPictures) {
string filename = Helper.CreateImageFilename(pair.Key.Shortname, pair.Value.Card.Name);
if(!File.Exists(filename)) {
if(!Directory.Exists("img\\" + pair.Key.Shortname + "\\")) {
Directory.CreateDirectory("img\\" + pair.Key.Shortname + "\\");
}
TimeSpan loadingTime;
Stopwatch watch = Stopwatch.StartNew();
DownloadImage(pair.Value.Url.AbsoluteUri, filename, card.MainType);
watch.Stop();
currentIndex++;
// calc laoding time
loadingTime = watch.Elapsed;
totalLoadingTime += loadingTime;
// calc total time
int imgToLoad = this.ItemsToLoad - this.CurrentItemAmount - currentIndex;
long ticks = (totalLoadingTime.Ticks / currentIndex);
totalTime = new TimeSpan(ticks * imgToLoad);
// raise event
if(this.ImageLoaderResponse != null) {
this.ImageLoaderResponse(new ImageLoaderEventArgs(
pair.Value.Card,
pair.Value.Edition,
index,
totalTime.GetValueOrDefault(),
totalLoadingTime
));
}
}
index++;
}
}
}
if(this.ImageLoaderFinish != null) {
this.ImageLoaderFinish(new ImageLoaderFinishEventArgs("All items successfull loaded!"));
}
}
示例8: OnStart
private IObservable<Unit> OnStart(TimeSpan? skipAhead) =>
this.Start(skipAhead.GetValueOrDefault(TimeSpan.Zero));
示例9: GetMillisDuration
public TimeSpan GetMillisDuration(string path, TimeSpan? @default = null)
{
HoconValue value = GetNode(path);
if (value == null)
return @default.GetValueOrDefault();
return value.GetMillisDuration();
}
示例10: LoadAssetAsync
/// <summary>Load an <see cref="Asset"/>.</summary>
/// <param name="loader"></param>
/// <param name="formats"></param>
/// <param name="resolveConflict"></param>
/// <param name="progress"></param>
/// <param name="progressUpdateRate"></param>
/// <returns></returns>
public static Task<Asset> LoadAssetAsync(AssetLoader loader, IEnumerable<AssetFormat> formats, ResolveLoadConflictCallback resolveConflict = null, AssetLoaderProgressCallback progress = null, TimeSpan? progressUpdateRate = null)
{
TimeSpan progressUpdateRateValue = progressUpdateRate.GetValueOrDefault(TimeSpan.FromSeconds(0.1));
LoadMatchStrength matchStrength;
AssetFormat format = LoadMatchAsset(out matchStrength, loader, formats, resolveConflict);
if (loader.Context != null)
loader.Context.LoadErrors = loader.Errors;
return new Task<Asset>(() => {
Asset asset = null;
bool complete = false;
Thread loadThread = new Thread(() => {
asset = format.Load(loader);
complete = true;
});
loadThread.Start();
while (!complete) {
if (!loadThread.IsAlive)
throw new InvalidOperationException("The load operation failed.");
Thread.Sleep(progressUpdateRateValue);
if (progress != null)
progress.Invoke(loader);
}
return asset;
});
}
示例11: CreatePolicy
static Func<ErrorContext, RecoverabilityAction> CreatePolicy(int maxImmediateRetries = 2, int maxDelayedRetries = 2, TimeSpan? delayedRetryDelay = null)
{
var config = new RecoverabilityConfig(new ImmediateConfig(maxImmediateRetries), new DelayedConfig(maxDelayedRetries, delayedRetryDelay.GetValueOrDefault(TimeSpan.FromSeconds(2))), new FailedConfig("errorQueue"));
return context => DefaultRecoverabilityPolicy.Invoke(config, context);
}
示例12: RepresentsRecentChange
//TODO:: add GSM and GPS status to events.
///// <summary>
///// GSM Strength
///// </summary>
//public double? GSMStrength { get; set; }
///// <summary>
///// GPS Connection
///// </summary>
//public double? GPSConnection { get; set; }
///// <summary>
///// GPS Lost Time
///// </summary>
//public double? GPSLostTime { get; set; }
///// <summary>
///// GPS State
///// </summary>
//public GpsState? GpsState { get; set; }
public override bool RepresentsRecentChange(TimeSpan? timeWindow)
{
return ((TimeSpan)(DateTime.UtcNow - Time)).TotalSeconds < timeWindow.GetValueOrDefault().TotalSeconds;
}
示例13: Shutdown
/// <summary>
/// Shuts down the specified system.
/// On failure debug output will be logged about the remaining actors in the system.
/// If verifySystemShutdown is true, then an exception will be thrown on failure.
/// </summary>
/// <param name="system">The system to shutdown.</param>
/// <param name="duration">The duration to wait for shutdown. Default is 5 seconds multiplied with the config value "akka.test.timefactor"</param>
/// <param name="verifySystemShutdown">if set to <c>true</c> an exception will be thrown on failure.</param>
protected virtual void Shutdown(ActorSystem system, TimeSpan? duration = null, bool verifySystemShutdown = false)
{
if (system == null) system = _testState.System;
var durationValue = duration.GetValueOrDefault(Dilated(TimeSpan.FromSeconds(5)).Min(TimeSpan.FromSeconds(10)));
var wasShutdownDuringWait = system.Terminate().Wait(durationValue);
if(!wasShutdownDuringWait)
{
const string msg = "Failed to stop [{0}] within [{1}] \n{2}";
if(verifySystemShutdown)
throw new TimeoutException(string.Format(msg, system.Name, durationValue, ""));
//TODO: replace "" with system.PrintTree()
system.Log.Warning(msg, system.Name, durationValue, ""); //TODO: replace "" with system.PrintTree()
}
}
示例14: ScheduleAdTrigger
/// <summary>
/// Schedules an ad that is to be handled by an AdPayloadHandlerPlugin.
/// A valid AdPayloadHandlerPlugin must be part of your application or this will not be handled.
/// </summary>
/// <param name="adTrigger">An object containing information about the ad source and target</param>
/// <param name="startTime">The position within the media where this ad should be played. If ommited ad will begin playing immediately.</param>
/// <returns>An object that contains information about the scheduled ad.</returns>
public ScheduledAd ScheduleAdTrigger(IAdSequencingTrigger adTrigger, TimeSpan? startTime = null)
{
var adStartTime = startTime.GetValueOrDefault(RelativeMediaPluginPosition);
var result = new ScheduledAd(adTrigger);
var adMarker = new AdMarker()
{
Immediate = !startTime.HasValue,
Begin = adStartTime,
Id = Guid.NewGuid().ToString(),
ScheduledAd = result,
End = adStartTime.Add(adTrigger.Duration.GetValueOrDefault(TimeSpan.FromDays(1))) // update the end based on the duration
};
// Immediate == true will trigger the timeline marker immediately instead of waiting for polling to occur
if (adMarker.Immediate)
{
var duration = adMarker.Duration;
adMarker.Begin = RelativeMediaPluginPosition;
adMarker.End = adMarker.Begin.Add(duration); // update the end based on the duration
AdMarkers.Add(adMarker);
// force a check on the postions, we know there is one that needs to be fired
if (!isSeekActive) _adMarkerManager.CheckMarkerPositions(RelativeMediaPluginPosition, AdMarkers, seekInProgress);
}
else
{
AdMarkers.Add(adMarker);
}
return result;
}
示例15: 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 = null)
{
var maxDur = RemainingOrDilated(max);
var interval = new TimeSpan(max.GetValueOrDefault().Ticks / 10);
InternalAwaitCondition(conditionIsFulfilled, maxDur, interval, message, (format, args) => _assertions.Fail(format, args));
}