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


C# TimeSpan.GetValueOrDefault方法代码示例

本文整理汇总了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);
		}
开发者ID:c1sc0,项目名称:elasticsearch-net,代码行数:7,代码来源:DateTimeProvider.cs

示例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;
 }
开发者ID:NoFlaw,项目名称:openaccess-orm-glimpse,代码行数:9,代码来源:OACommandExecuted.cs

示例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.");
		}
开发者ID:ExM,项目名称:NConfiguration,代码行数:13,代码来源:WatchedFileChecker.cs

示例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);
        }
开发者ID:CLupica,项目名称:ServiceStack,代码行数:13,代码来源:CsvRequestLogger.cs

示例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;
 }
开发者ID:JackWangCUMT,项目名称:Bumpkit,代码行数:20,代码来源:GifEncoder.cs

示例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);
     }
 }
开发者ID:rodrigovidal,项目名称:akka.net,代码行数:38,代码来源:TestKitBase_AwaitAssert.cs

示例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!"));
            }
        }
开发者ID:vandango,项目名称:Lhurgoyf,代码行数:57,代码来源:ImageLoader.cs

示例8: OnStart

 private IObservable<Unit> OnStart(TimeSpan? skipAhead) =>
     this.Start(skipAhead.GetValueOrDefault(TimeSpan.Zero));
开发者ID:gregjones60,项目名称:WorkoutWotch,代码行数:2,代码来源:ExerciseProgramViewModel.cs

示例9: GetMillisDuration

        public TimeSpan GetMillisDuration(string path, TimeSpan? @default = null)
        {
            HoconValue value = GetNode(path);
            if (value == null)
                return @default.GetValueOrDefault();

            return value.GetMillisDuration();
        }
开发者ID:rmiller1971,项目名称:akka.net,代码行数:8,代码来源:Config.cs

示例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;
            });
        }
开发者ID:Burton-Radons,项目名称:Alexandria,代码行数:37,代码来源:AssetFormat.cs

示例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);
 }
开发者ID:Particular,项目名称:NServiceBus,代码行数:5,代码来源:DefaultRecoverabilityPolicyTests.cs

示例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;
        }
开发者ID:gao1183,项目名称:Mojio.Client,代码行数:25,代码来源:Event.cs

示例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()
            }
        }
开发者ID:juergenhoetzel,项目名称:akka.net,代码行数:24,代码来源:TestKitBase.cs

示例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;
        }
开发者ID:Ginichen,项目名称:Silverlight-Player-for-PlayReady-with-Token-Auth,代码行数:38,代码来源:SMFPlayer.cs

示例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));
 }
开发者ID:ClusterReply,项目名称:akka.net,代码行数:25,代码来源:TestKitBase_AwaitConditions.cs


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