System.Threading.Tasks.Task.Delay(System.TimeSpan)

Here are the examples of the csharp api System.Threading.Tasks.Task.Delay(System.TimeSpan) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1689 Examples 7

19 Source : SpamContext.cs
with MIT License
from 0x0ade

public bool Add() {
                lock (Spam.Timeouts) {
                    if (Count < Spam.Chat.Settings.SpamCountMax) {
                        Count++;

                        Task.Run(async () => {
                            await Task.Delay(TimeSpan.FromSeconds(Spam.Chat.Settings.SpamTimeoutAdd));
                            lock (Spam.Timeouts) {
                                if (Unspammed)
                                    return;
                                Count--;
                                if ((!Spammed || Timeout.Ticks <= 0) && Count <= 0)
                                    Spam.Timeouts.Remove(Text);
                            }
                        });
                    }

                    if (Spammed || Count >= Spam.Chat.Settings.SpamCount) {
                        if (!Spammed)
                            Start = DateTime.UtcNow;
                        Spammed = true;
                        Task.Run(async () => {
                            TimeSpan timeout = Timeout;
                            if (timeout.Ticks > 0)
                                await Task.Delay(timeout);
                            lock (Spam.Timeouts) {
                                if (Unspammed)
                                    return;
                                if (Count <= 0) {
                                    Unspammed = true;
                                    Spam.Timeouts.Remove(Text);
                                }
                            }
                        });
                        return true;
                    }

                    return false;
                }
            }

19 Source : PersonService.cs
with MIT License
from 1100100

public async Task<object> GetName(int id)
        {
            await Task.Delay(TimeSpan.FromHours(1));
            return await Task.FromResult(new
            {
                name = $"[{id}]Owen",
                //message = await HelloService.SayHello("Owen")
            });
        }

19 Source : RedisConfigurationProvider.cs
with GNU Lesser General Public License v3.0
from 8720826

private async void ListenToConfigurationChanges()
        {
            if (_source.ReloadTime <= 0)
                return;

            while (true)
            {
                try
                {
                    await Task.Delay(TimeSpan.FromSeconds(_source.ReloadTime));
                    await LoadData();
                    
                    OnReload();
                }
                catch
                {
                }
            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from ABTSoftware

private async void MainWindowLoaded(object sender, RoutedEventArgs e)
        {
            // Wait for the license initialization we triggered in App.xaml.cs
            await SciChart2D3DInitializer.Awaiter;

            // Dumps licensing info to console
            Console.WriteLine(SciChartSurface.DumpInfo());

            ((LoadingContent) this.root.Children[0]).StopTimer();

            // SciChart 6.2.0's license init is so fast that we put this awaiter in just so you can see the loading screen with time to initialize
            // Remove it in your app, its not necessary 
            await Task.Delay(TimeSpan.FromMilliseconds(500));

            // Now swap out content for SciChartSurfaces once licenses loaded 
            this.root.Children.Add(new SciChartContent());
            this.root.Children.RemoveAt(0);
        }

19 Source : AwaitExtensions.cs
with MIT License
from Accelerider

public static TaskAwaiter GetAwaiter(this TimeSpan timeSpan)
        {
            return Task.Delay(timeSpan).GetAwaiter();
        }

19 Source : Program.cs
with MIT License
from Accelerider

public static async Task Main(string[] args)
        {
            var launcherArgs = ParseLauncherArgs(args);

            if (launcherArgs.Delay > 0)
            {
                await Task.Delay(TimeSpan.FromMilliseconds(launcherArgs.Delay));
            }

            // 1. Find the latest version bin folder.
            var bins = GetBinDirectories(CurrentDirectory).ToList();
            if (!bins.Any()) return;

            bins.Sort((x, y) => x.Version > y.Version ? -1 : 1);

            foreach (var bin in bins)
            {
                // 2. Try to start the main program.
                try
                {
                    var process = new Process
                    {
                        StartInfo =
                        {
                            FileName = Path.Combine(bin.DirectoryName, MainProgramName),
                            WindowStyle = ProcessWindowStyle.Hidden,
                            Arguments = launcherArgs.AutoLogin ? "--auto-login" : string.Empty
                        }
                    };
                    process.Start();

                    // 3. Clear history versions.
                    foreach (var directory in bins.Where(item => !bin.Equals(item)))
                    {
                        await DeleteDirectoryAsync(directory.DirectoryName);
                    }
                }
                catch (Win32Exception)
                {
                    // TODO: Logging or Notify.
                    await DeleteDirectoryAsync(bin.DirectoryName);
                }
            }
        }

19 Source : Program.cs
with MIT License
from Accelerider

private static async Task DeleteDirectoryAsync(string path, int count = 0)
        {
            try
            {
                Directory.Delete(path, true);
            }
            catch (IOException)
            {
                if (count < 10)
                {
                    await Task.Delay(TimeSpan.FromMilliseconds(500 * count));
                    await DeleteDirectoryAsync(path, count + 1);
                }
            }
        }

19 Source : JobNotification.cs
with MIT License
from actions

private async Task EndMonitor()
        {
            try
            {
                Trace.Info("Entering EndMonitor");
                if (_isMonitorConfigured)
                {
                    String message = $"End {System.Diagnostics.Process.GetCurrentProcess().Id}";
                    Trace.Info("Writing EndMonitor to socket");
                    _monitorSocket.Send(Encoding.UTF8.GetBytes(message));
                    Trace.Info("Finished EndMonitor writing to socket");

                    await Task.Delay(TimeSpan.FromSeconds(2));                    
                }
            }
            catch (SocketException e)
            {
                Trace.Error($"Failed sending end message on socket!");
                Trace.Error(e);
            }
            catch (Exception e)
            {
                Trace.Error($"Unexpected error occurred while sending StartMonitor message on socket!");
                Trace.Error(e);
            }
        }

19 Source : JobServer.cs
with MIT License
from actions

public async Task ConnectAsync(VssConnection jobConnection)
        {
            _connection = jobConnection;
            int totalAttempts = 5;
            int attemptCount = totalAttempts;
            var configurationStore = HostContext.GetService<IConfigurationStore>();
            var runnerSettings = configurationStore.GetSettings();
 
            while (!_connection.HasAuthenticated && attemptCount-- > 0)
            {
                try
                {
                    await _connection.ConnectAsync();
                    break;
                }
                catch (Exception ex) when (attemptCount > 0)
                {
                    Trace.Info($"Catch exception during connect. {attemptCount} attempts left.");
                    Trace.Error(ex);

                    if (runnerSettings.IsHostedServer)
                    {
                        await CheckNetworkEndpointsAsync(attemptCount);
                    }
                }

                int attempt = totalAttempts - attemptCount;
                TimeSpan backoff = BackoffTimerHelper.GetExponentialBackoff(attempt, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(3.2), TimeSpan.FromMilliseconds(100));

                await Task.Delay(backoff);
            }

            _taskClient = _connection.GetClient<TaskHttpClient>();
            _hasConnection = true;
        }

19 Source : JobServerQueue.cs
with MIT License
from actions

private async Task ProcessWebConsoleLinesQueueAsync(bool runOnce = false)
        {
            while (!_jobCompletionSource.Task.IsCompleted || runOnce)
            {
                if (_webConsoleLineAggressiveDequeue && ++_webConsoleLineAggressiveDequeueCount > _webConsoleLineAggressiveDequeueLimit)
                {
                    Trace.Info("Stop aggressive process web console line queue.");
                    _webConsoleLineAggressiveDequeue = false;
                }

                // Group consolelines by timeline record of each step
                Dictionary<Guid, List<TimelineRecordLogLine>> stepsConsoleLines = new Dictionary<Guid, List<TimelineRecordLogLine>>();
                List<Guid> stepRecordIds = new List<Guid>(); // We need to keep lines in order
                int linesCounter = 0;
                ConsoleLineInfo lineInfo;
                while (_webConsoleLineQueue.TryDequeue(out lineInfo))
                {
                    if (!stepsConsoleLines.ContainsKey(lineInfo.StepRecordId))
                    {
                        stepsConsoleLines[lineInfo.StepRecordId] = new List<TimelineRecordLogLine>();
                        stepRecordIds.Add(lineInfo.StepRecordId);
                    }

                    if (!string.IsNullOrEmpty(lineInfo.Line) && lineInfo.Line.Length > 1024)
                    {
                        Trace.Verbose("Web console line is more than 1024 chars, truncate to first 1024 chars");
                        lineInfo.Line = $"{lineInfo.Line.Substring(0, 1024)}...";
                    }

                    stepsConsoleLines[lineInfo.StepRecordId].Add(new TimelineRecordLogLine(lineInfo.Line, lineInfo.LineNumber));
                    linesCounter++;

                    // process at most about 500 lines of web console line during regular timer dequeue task.
                    if (!runOnce && linesCounter > 500)
                    {
                        break;
                    }
                }

                // Batch post consolelines for each step timeline record
                foreach (var stepRecordId in stepRecordIds)
                {
                    // Split consolelines into batch, each batch will container at most 100 lines.
                    int batchCounter = 0;
                    List<List<TimelineRecordLogLine>> batchedLines = new List<List<TimelineRecordLogLine>>();
                    foreach (var line in stepsConsoleLines[stepRecordId])
                    {
                        var currentBatch = batchedLines.ElementAtOrDefault(batchCounter);
                        if (currentBatch == null)
                        {
                            batchedLines.Add(new List<TimelineRecordLogLine>());
                            currentBatch = batchedLines.ElementAt(batchCounter);
                        }

                        currentBatch.Add(line);

                        if (currentBatch.Count >= 100)
                        {
                            batchCounter++;
                        }
                    }

                    if (batchedLines.Count > 0)
                    {
                        // When job finish, web console lines becomes less interesting to customer
                        // We batch and produce 500 lines of web console output every 500ms
                        // If customer's task produce mreplacedive of outputs, then the last queue drain run might take forever.
                        // So we will only upload the last 200 lines of each step from all buffered web console lines.
                        if (runOnce && batchedLines.Count > 2)
                        {
                            Trace.Info($"Skip {batchedLines.Count - 2} batches web console lines for last run");
                            batchedLines = batchedLines.TakeLast(2).ToList();
                        }

                        int errorCount = 0;
                        foreach (var batch in batchedLines)
                        {
                            try
                            {
                                // we will not requeue failed batch, since the web console lines are time sensitive.
                                if (batch[0].LineNumber.HasValue)
                                {
                                    await _jobServer.AppendTimelineRecordFeedAsync(_scopeIdentifier, _hubName, _planId, _jobTimelineId, _jobTimelineRecordId, stepRecordId, batch.Select(logLine => logLine.Line).ToList(), batch[0].LineNumber.Value, default(CancellationToken));
                                }
                                else
                                {
                                    await _jobServer.AppendTimelineRecordFeedAsync(_scopeIdentifier, _hubName, _planId, _jobTimelineId, _jobTimelineRecordId, stepRecordId, batch.Select(logLine => logLine.Line).ToList(), default(CancellationToken));
                                }

                                if (_firstConsoleOutputs)
                                {
                                    HostContext.WritePerfCounter($"WorkerJobServerQueueAppendFirstConsoleOutput_{_planId.ToString()}");
                                    _firstConsoleOutputs = false;
                                }
                            }
                            catch (Exception ex)
                            {
                                Trace.Info("Catch exception during append web console line, keep going since the process is best effort.");
                                Trace.Error(ex);
                                errorCount++;
                            }
                        }

                        Trace.Info("Try to append {0} batches web console lines for record '{2}', success rate: {1}/{0}.", batchedLines.Count, batchedLines.Count - errorCount, stepRecordId);
                    }
                }

                if (runOnce)
                {
                    break;
                }
                else
                {
                    await Task.Delay(_webConsoleLineAggressiveDequeue ? _aggressiveDelayForWebConsoleLineDequeue : _delayForWebConsoleLineDequeue);
                }
            }
        }

19 Source : JobServerQueue.cs
with MIT License
from actions

private async Task ProcessFilesUploadQueueAsync(bool runOnce = false)
        {
            while (!_jobCompletionSource.Task.IsCompleted || runOnce)
            {
                List<UploadFileInfo> filesToUpload = new List<UploadFileInfo>();
                UploadFileInfo dequeueFile;
                while (_fileUploadQueue.TryDequeue(out dequeueFile))
                {
                    filesToUpload.Add(dequeueFile);
                    // process at most 10 file upload.
                    if (!runOnce && filesToUpload.Count > 10)
                    {
                        break;
                    }
                }

                if (filesToUpload.Count > 0)
                {
                    if (runOnce)
                    {
                        Trace.Info($"Uploading {filesToUpload.Count} files in one shot.");
                    }

                    // TODO: upload all file in parallel
                    int errorCount = 0;
                    foreach (var file in filesToUpload)
                    {
                        try
                        {
                            await UploadFile(file);
                        }
                        catch (Exception ex)
                        {
                            Trace.Info("Catch exception during log or attachment file upload, keep going since the process is best effort.");
                            Trace.Error(ex);
                            errorCount++;

                            // put the failed upload file back to queue.
                            // TODO: figure out how should we retry paging log upload.
                            //lock (_fileUploadQueueLock)
                            //{
                            //    _fileUploadQueue.Enqueue(file);
                            //}
                        }
                    }

                    Trace.Info("Try to upload {0} log files or attachments, success rate: {1}/{0}.", filesToUpload.Count, filesToUpload.Count - errorCount);
                }

                if (runOnce)
                {
                    break;
                }
                else
                {
                    await Task.Delay(_delayForFileUploadDequeue);
                }
            }
        }

19 Source : JobServerQueue.cs
with MIT License
from actions

private async Task ProcessTimelinesUpdateQueueAsync(bool runOnce = false)
        {
            while (!_jobCompletionSource.Task.IsCompleted || runOnce)
            {
                List<PendingTimelineRecord> pendingUpdates = new List<PendingTimelineRecord>();
                foreach (var timeline in _allTimelines)
                {
                    ConcurrentQueue<TimelineRecord> recordQueue;
                    if (_timelineUpdateQueue.TryGetValue(timeline, out recordQueue))
                    {
                        List<TimelineRecord> records = new List<TimelineRecord>();
                        TimelineRecord record;
                        while (recordQueue.TryDequeue(out record))
                        {
                            records.Add(record);
                            // process at most 25 timeline records update for each timeline.
                            if (!runOnce && records.Count > 25)
                            {
                                break;
                            }
                        }

                        if (records.Count > 0)
                        {
                            pendingUpdates.Add(new PendingTimelineRecord() { TimelineId = timeline, PendingRecords = records.ToList() });
                        }
                    }
                }

                // we need track whether we have new sub-timeline been created on the last run.
                // if so, we need continue update timeline record even we on the last run.
                bool pendingSubtimelineUpdate = false;
                List<Exception> mainTimelineRecordsUpdateErrors = new List<Exception>();
                if (pendingUpdates.Count > 0)
                {
                    foreach (var update in pendingUpdates)
                    {
                        List<TimelineRecord> bufferedRecords;
                        if (_bufferedRetryRecords.TryGetValue(update.TimelineId, out bufferedRecords))
                        {
                            update.PendingRecords.InsertRange(0, bufferedRecords);
                        }

                        update.PendingRecords = MergeTimelineRecords(update.PendingRecords);

                        foreach (var detailTimeline in update.PendingRecords.Where(r => r.Details != null))
                        {
                            if (!_allTimelines.Contains(detailTimeline.Details.Id))
                            {
                                try
                                {
                                    Timeline newTimeline = await _jobServer.CreateTimelineAsync(_scopeIdentifier, _hubName, _planId, detailTimeline.Details.Id, default(CancellationToken));
                                    _allTimelines.Add(newTimeline.Id);
                                    pendingSubtimelineUpdate = true;
                                }
                                catch (TimelineExistsException)
                                {
                                    Trace.Info("Catch TimelineExistsException during timeline creation. Ignore the error since server already had this timeline.");
                                    _allTimelines.Add(detailTimeline.Details.Id);
                                }
                                catch (Exception ex)
                                {
                                    Trace.Error(ex);
                                }
                            }
                        }

                        try
                        {
                            await _jobServer.UpdateTimelineRecordsAsync(_scopeIdentifier, _hubName, _planId, update.TimelineId, update.PendingRecords, default(CancellationToken));
                            if (_bufferedRetryRecords.Remove(update.TimelineId))
                            {
                                Trace.Verbose("Cleanup buffered timeline record for timeline: {0}.", update.TimelineId);
                            }

                            if (!_jobRecordUpdated.Task.IsCompleted &&
                                update.PendingRecords.Any(x => x.Id == _jobTimelineRecordId && x.State != null))
                            {
                                // We have changed the state of the job
                                Trace.Info("Job timeline record has been updated for the first time.");
                                _jobRecordUpdated.TrySetResult(0);
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Info("Catch exception during update timeline records, try to update these timeline records next time.");
                            Trace.Error(ex);
                            _bufferedRetryRecords[update.TimelineId] = update.PendingRecords.ToList();
                            if (update.TimelineId == _jobTimelineId)
                            {
                                mainTimelineRecordsUpdateErrors.Add(ex);
                            }
                        }
                    }
                }

                if (runOnce)
                {
                    // continue process timeline records update, 
                    // we might have more records need update, 
                    // since we just create a new sub-timeline
                    if (pendingSubtimelineUpdate)
                    {
                        continue;
                    }
                    else
                    {
                        if (mainTimelineRecordsUpdateErrors.Count > 0 &&
                            _bufferedRetryRecords.ContainsKey(_jobTimelineId) &&
                            _bufferedRetryRecords[_jobTimelineId] != null &&
                            _bufferedRetryRecords[_jobTimelineId].Any(r => r.Variables.Count > 0))
                        {
                            Trace.Info("Fail to update timeline records with output variables. Throw exception to fail the job since output variables are critical to downstream jobs.");
                            throw new AggregateException("Failed to publish output variables.", mainTimelineRecordsUpdateErrors);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    await Task.Delay(_delayForTimelineUpdateDequeue);
                }
            }
        }

19 Source : ProcessInvoker.cs
with MIT License
from actions

private void ProcessExitedHandler(object sender, EventArgs e)
        {
            if ((_proc.StartInfo.RedirectStandardError || _proc.StartInfo.RedirectStandardOutput) && _asyncStreamReaderCount != 0)
            {
                _waitingOnStreams = true;

                Task.Run(async () =>
                {
                    // Wait 5 seconds and then Cancel/Kill process tree
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    KillProcessTree();
                    _processExitedCompletionSource.TrySetResult(true);
                    _processStandardInWriteCancellationTokenSource.Cancel();
                });
            }
            else
            {
                _processExitedCompletionSource.TrySetResult(true);
                _processStandardInWriteCancellationTokenSource.Cancel();
            }
        }

19 Source : ProcessInvoker.cs
with MIT License
from actions

private async Task<bool> SendSignal(Signals signal, TimeSpan timeout)
        {
            Trace.Info($"Sending {signal} to process {_proc.Id}.");
            int errorCode = kill(_proc.Id, (int)signal);
            if (errorCode != 0)
            {
                Trace.Info($"{signal} signal doesn't fire successfully.");
                Trace.Info($"Error code: {errorCode}.");
                return false;
            }

            Trace.Info($"Successfully send {signal} to process {_proc.Id}.");
            Trace.Info($"Waiting for process exit or {timeout.TotalSeconds} seconds after {signal} signal fired.");
            var completedTask = await Task.WhenAny(Task.Delay(timeout), _processExitedCompletionSource.Task);
            if (completedTask == _processExitedCompletionSource.Task)
            {
                Trace.Info("Process exit successfully.");
                return true;
            }
            else
            {
                Trace.Info($"Process did not honor {signal} signal within {timeout.TotalSeconds} seconds.");
                return false;
            }
        }

19 Source : ExecutionContext.cs
with MIT License
from actions

public void ForceTaskComplete()
        {
            Trace.Info("Force finish current task in 5 sec.");
            Task.Run(async () =>
            {
                await Task.Delay(TimeSpan.FromSeconds(5));
                _forceCompleted?.TrySetResult(1);
            });
        }

19 Source : JobRunner.cs
with MIT License
from actions

private async Task<TaskResult> CompleteJobAsync(IJobServer jobServer, IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, TaskResult? taskResult = null)
        {
            jobContext.Debug($"Finishing: {message.JobDisplayName}");
            TaskResult result = jobContext.Complete(taskResult);

            try
            {
                await ShutdownQueue(throwOnFailure: true);
            }
            catch (Exception ex)
            {
                Trace.Error($"Caught exception from {nameof(JobServerQueue)}.{nameof(_jobServerQueue.ShutdownAsync)}");
                Trace.Error("This indicate a failure during publish output variables. Fail the job to prevent unexpected job outputs.");
                Trace.Error(ex);
                result = TaskResultUtil.MergeTaskResults(result, TaskResult.Failed);
            }

            // Clean TEMP after finish process jobserverqueue, since there might be a pending fileupload still use the TEMP dir.
            _tempDirectoryManager?.CleanupTempDirectory();

            if (!jobContext.Global.Features.HasFlag(PlanFeatures.JobCompletedPlanEvent))
            {
                Trace.Info($"Skip raise job completed event call from worker because Plan version is {message.Plan.Version}");
                return result;
            }

            // Load any upgrade telemetry
            LoadFromTelemetryFile(jobContext.JobTelemetry);

            // Make sure we don't submit secrets as telemetry
            MaskTelemetrySecrets(jobContext.JobTelemetry);

            Trace.Info("Raising job completed event.");
            var jobCompletedEvent = new JobCompletedEvent(message.RequestId, message.JobId, result, jobContext.JobOutputs, jobContext.ActionsEnvironment, jobContext.ActionsStepsTelemetry, jobContext.JobTelemetry);


            var completeJobRetryLimit = 5;
            var exceptions = new List<Exception>();
            while (completeJobRetryLimit-- > 0)
            {
                try
                {
                    await jobServer.RaisePlanEventAsync(message.Plan.ScopeIdentifier, message.Plan.PlanType, message.Plan.PlanId, jobCompletedEvent, default(CancellationToken));
                    return result;
                }
                catch (TaskOrchestrationPlanNotFoundException ex)
                {
                    Trace.Error($"TaskOrchestrationPlanNotFoundException received, while attempting to raise JobCompletedEvent for job {message.JobId}.");
                    Trace.Error(ex);
                    return TaskResult.Failed;
                }
                catch (TaskOrchestrationPlanSecurityException ex)
                {
                    Trace.Error($"TaskOrchestrationPlanSecurityException received, while attempting to raise JobCompletedEvent for job {message.JobId}.");
                    Trace.Error(ex);
                    return TaskResult.Failed;
                }
                catch (TaskOrchestrationPlanTerminatedException ex)
                {
                    Trace.Error($"TaskOrchestrationPlanTerminatedException received, while attempting to raise JobCompletedEvent for job {message.JobId}.");
                    Trace.Error(ex);
                    return TaskResult.Failed;
                }
                catch (Exception ex)
                {
                    Trace.Error($"Catch exception while attempting to raise JobCompletedEvent for job {message.JobId}, job request {message.RequestId}.");
                    Trace.Error(ex);
                    exceptions.Add(ex);
                }

                // delay 5 seconds before next retry.
                await Task.Delay(TimeSpan.FromSeconds(5));
            }

            // rethrow exceptions from all attempts.
            throw new AggregateException(exceptions);
        }

19 Source : TestHostContext.cs
with MIT License
from actions

public async Task Delay(TimeSpan delay, CancellationToken token)
        {
            await Task.Delay(TimeSpan.Zero);
        }

19 Source : BankIdSimulatedApiClient.cs
with MIT License
from ActiveLogin

private async Task SimulateResponseDelay()
        {
            await Task.Delay(Delay).ConfigureAwait(false);
        }

19 Source : FlowConnectionManager.cs
with GNU General Public License v3.0
from Adam-Wilkinson

private void FlashColourChange()
        {
            _instance.UIContext.Post(delegate { HexColour.Value = "#F000F0"; }, null);
            Task.Delay(new TimeSpan(0, 0, 0, 0, 300)).ContinueWith(t =>
            {
                _instance.UIContext.Post(delegate { HexColour.Value = "#800080"; }, null);
            });
        }

19 Source : EdgeCasesTest.cs
with MIT License
from adams85

[Fact]
        public async Task FailingEntryDontGetStuck()
        {
            var logsDirName = Guid.NewGuid().ToString("D");

            var tempPath = Path.Combine(Path.GetTempPath());
            var logPath = Path.Combine(tempPath, logsDirName);

            if (Directory.Exists(logPath))
                Directory.Delete(logPath, recursive: true);

            var fileProvider = new PhysicalFileProvider(tempPath);

            var options = new FileLoggerOptions
            {
                FileAppender = new PhysicalFileAppender(fileProvider),
                BasePath = logsDirName,
                Files = new[]
                {
                    new LogFileOptions
                    {
                        Path = "default.log",
                    },
                },
            };
            var optionsMonitor = new DelegatedOptionsMonitor<FileLoggerOptions>(_ => options);

            var completeCts = new CancellationTokenSource();
            var completionTimeoutMs = 2000;
            var context = new TestFileLoggerContext(completeCts.Token, TimeSpan.FromMilliseconds(completionTimeoutMs), writeRetryDelay: TimeSpan.FromMilliseconds(250));
            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(b => b.AddFile(context));
            services.AddSingleton<IOptionsMonitor<FileLoggerOptions>>(optionsMonitor);

            string filePath = Path.Combine(logPath, "default.log");

            try
            {
                FileLoggerProvider[] providers;

                using (ServiceProvider sp = services.BuildServiceProvider())
                {
                    providers = context.GetProviders(sp).ToArray();
                    replacedert.Equal(1, providers.Length);

                    var resetTasks = new List<Task>();
                    foreach (FileLoggerProvider provider in providers)
                        provider.Reset += (s, e) => resetTasks.Add(e);

                    ILoggerFactory loggerFactory = sp.GetRequiredService<ILoggerFactory>();
                    ILogger logger = loggerFactory.CreateLogger("X");

                    logger.LogInformation("This should get through.");

                    optionsMonitor.Reload();
                    // ensuring that reset has been finished and the new settings are effective
                    await Task.WhenAll(resetTasks);

                    using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        logger.LogInformation("This shouldn't get through.");

                        Task completion = context.GetCompletion(sp);
                        replacedert.False(completion.IsCompleted);

                        completeCts.Cancel();

                        replacedert.Equal(completion, await Task.WhenAny(completion, Task.Delay(TimeSpan.FromMilliseconds(completionTimeoutMs * 2))));
                        replacedert.Equal(TaskStatus.RanToCompletion, completion.Status);
                    }
                }

                IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/default.log");
                replacedert.True(logFile.Exists && !logFile.IsDirectory);

                var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                replacedert.Equal(Encoding.UTF8, encoding);
                replacedert.Equal(new[]
                {
                    $"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                    $"      This should get through.",
                    ""
                }, lines);
            }
            finally
            {
                Directory.Delete(logPath, recursive: true);
            }
        }

19 Source : AsyncHelper.cs
with MIT License
from AdemCatamak

public static async Task WaitFor(TimeSpan wait, double times = 1)
        {
            double waitTotalMilliseconds = wait.TotalMilliseconds * times;
            TimeSpan result = TimeSpan.FromMilliseconds(waitTotalMilliseconds);

            await Task.Delay(result);
        }

19 Source : SimpleAudioPlayerImplementation.cs
with MIT License
from adrianstevens

public async Task SeekToAsync(int msec)
		{
			try
			{
				if (player != null)
				{
					if (player.State == PlayerState.Ready || player.State == PlayerState.Playing || player.State == PlayerState.Paused)
					{
						if (lastRequestedSeekPosition == msec || player == null)
							return;

						var nowTicks = DateTime.Now.Ticks;
						lastRequestedSeekPosition = msec;

						if (previousSeekTime == -1L)
							previousSeekTime = nowTicks;

						var diffInMilliseconds = (nowTicks - previousSeekTime) / TimeSpan.TicksPerMillisecond;
						if (diffInMilliseconds < 1000)
							await Task.Delay(TimeSpan.FromMilliseconds(2000));
						if (player == null)
							return;

						previousSeekTime = nowTicks;
						if (lastRequestedSeekPosition != msec)
							return;

						await player.SetPlayPositionAsync(lastRequestedSeekPosition, false);
						lastRequestedSeekPosition = -1;
					}
				}
				else
					return;
			}
			catch (Exception ex)
			{
				throw new Exception(ex.Message);
			}
		}

19 Source : Index.razor.cs
with MIT License
from AdrianWilczynski

private async Task OnSetRandomThemeClick()
        {
            if (IsSettingRandomThemeInProgress)
            {
                return;
            }

            IsSettingRandomThemeInProgress = true;

            var steps = new Random().Next(1, Constants.Themes.Count);

            for (int i = 0; i < steps; i++)
            {
                if (i != 0)
                {
                    await Task.Delay(TimeSpan.FromSeconds(0.25));
                }

                await OnChangeThemeClick();
                StateHasChanged();
            }

            IsSettingRandomThemeInProgress = false;
        }

19 Source : Kissing.cs
with GNU General Public License v3.0
from aedenthorn

public static void TrySpousesKiss(GameLocation location)
        {

            if ( location == null || Game1.eventUp || Game1.activeClickableMenu != null || Game1.player.currentLocation != location || (!Config.AllowNPCSpousesToKiss && !Config.AllowPlayerSpousesToKiss && !Config.AllowNPCRelativesToHug))
                return;

            elapsedSeconds++;

            var characters = location.characters;
            if (characters == null)
                return;

            List<NPC> list = characters.ToList();

            Misc.ShuffleList(ref list);

            foreach (NPC npc1 in list)
            {
                if (!npc1.datable.Value && !npc1.isRoommate() && !Config.AllowNonDateableNPCsToHugAndKiss)
                    continue;

                foreach (NPC npc2 in list)
                {
                    if (npc1.Name == npc2.Name)
                        continue;

                    if (!npc2.datable.Value && !Config.AllowNonDateableNPCsToHugAndKiss)
                        continue;

                    if (lastKissed.ContainsKey(npc1.Name) && elapsedSeconds - lastKissed[npc1.Name] <= Config.MinSpouseKissIntervalSeconds)
                        continue;

                    if (lastKissed.ContainsKey(npc2.Name) && elapsedSeconds - lastKissed[npc2.Name] <= Config.MinSpouseKissIntervalSeconds)
                        continue;

                    bool npcRelatedHug = Misc.AreNPCsRelated(npc1.Name, npc2.Name) && Config.AllowNPCRelativesToHug;
                    bool npcRoommateHug = !Config.RoommateKisses && (npc1.isRoommate() || npc2.isRoommate());
                    
                    bool npcMarriageKiss = Misc.AreNPCsMarried(npc1.Name, npc2.Name) && Config.AllowNPCSpousesToKiss;
                    bool playerSpouseKiss = Config.AllowPlayerSpousesToKiss &&
                        npc1.getSpouse() != null && npc2.getSpouse() != null &&
                        npc1.getSpouse() == npc2.getSpouse() &&
                        npc1.getSpouse().friendshipData.ContainsKey(npc1.Name) && npc1.getSpouse().friendshipData.ContainsKey(npc2.Name) &&
                        (Config.RoommateKisses || !npc1.getSpouse().friendshipData[npc1.Name].RoommateMarriage) && (Config.RoommateKisses || !npc1.getSpouse().friendshipData[npc2.Name].RoommateMarriage) &&
                        npc1.getSpouse().getFriendshipHeartLevelForNPC(npc1.Name) >= Config.MinHeartsForMarriageKiss && npc1.getSpouse().getFriendshipHeartLevelForNPC(npc2.Name) >= Config.MinHeartsForMarriageKiss &&
                        (Config.AllowRelativesToKiss || !Misc.AreNPCsRelated(npc1.Name, npc2.Name));

                    // check if spouses
                    if (!npcMarriageKiss && !npcRelatedHug && !playerSpouseKiss && !npcRoommateHug)
                        continue;

                    float distance = Vector2.Distance(npc1.position, npc2.position);
                    if (
                        distance < Config.MaxDistanceToKiss
                        && !npc1.isSleeping.Value
                        && !npc2.isSleeping.Value
                        && ModEntry.myRand.NextDouble() < Config.SpouseKissChance0to1
                    )
                    {
                        Monitor.Log($"{npc1.Name} and {npc2.Name} are marriage kissing: {npcMarriageKiss}, related hugging: {npcRelatedHug}, player spouse kissing: {playerSpouseKiss}");

                        lastKissed[npc1.Name] = elapsedSeconds;
                        lastKissed[npc2.Name] = elapsedSeconds;

                        Vector2 npc1pos = npc1.position;
                        Vector2 npc2pos = npc2.position;
                        int npc1face = npc1.facingDirection;
                        int npc2face = npc1.facingDirection;
                        Vector2 midpoint = new Vector2((npc1.position.X + npc2.position.X) / 2, (npc1.position.Y + npc2.position.Y) / 2);

                        PerformEmbrace(npc1, midpoint, npc2.Name);
                        PerformEmbrace(npc2, midpoint, npc1.Name);

                        if (playerSpouseKiss || npcMarriageKiss)
                        {
                            if (Config.CustomKissSound.Length > 0 && kissEffect != null)
                            {
                                float playerDistance = 1f / ((Vector2.Distance(midpoint, Game1.player.position) / 256) + 1);
                                kissEffect.Play(playerDistance * Game1.options.soundVolumeLevel, 0, 0);
                            }
                            else
                            {
                                Game1.currentLocation.playSound("dwop", NetAudio.SoundContext.NPC);
                            }
                            Misc.ShowHeart(npc1);
                            Misc.ShowHeart(npc2);

                        }
                        else
                        {
                            if (Config.CustomHugSound.Length > 0 && hugEffect != null)
                            {
                                float playerDistance = 1f / ((Vector2.Distance(midpoint, Game1.player.position) / 256) + 1);
                                hugEffect.Play(playerDistance * Game1.options.soundVolumeLevel, 0, 0);
                            }
                            Misc.ShowSmiley(npc1);
                            Misc.ShowSmiley(npc2);
                        }

                        DelayedAction action = new DelayedAction(1000);
                        var t = Task.Run(async delegate
                        {
                            await Task.Delay(TimeSpan.FromSeconds(1f));
                            npc1.position.Value = npc1pos;
                            npc2.position.Value = npc2pos;
                            npc1.FacingDirection = npc1face;
                            npc2.FacingDirection = npc2face;
                            npc1.Sprite.UpdateSourceRect();
                            npc2.Sprite.UpdateSourceRect();
                            return;
                        });
                    }
                }
            }
        }

19 Source : Kissing.cs
with GNU General Public License v3.0
from aedenthorn

public static void TrySpousesKiss()
        {
            GameLocation location = Game1.currentLocation;

            if (location == null || !ReferenceEquals(location.GetType(), typeof(FarmHouse)))
                return;

            Farmer owner = (location as FarmHouse).owner;

            lastKissTime++;

            if (location == null || location.characters == null)
                return;

            List<NPC> list = location.characters.ToList();

            Misc.ShuffleList(ref list);

            foreach (NPC npc1 in list)
            {
                if (!owner.friendshipData.ContainsKey(npc1.Name))
                    continue;

                if (!ModEntry.config.RoommateRomance && owner.friendshipData[npc1.Name].RoommateMarriage)
                {
                    continue;
                }


                foreach (NPC npc2 in list)
                {
                    if (!owner.friendshipData.ContainsKey(npc2.Name))
                        continue;

                    if (npc1.Name == npc2.Name || (!ModEntry.config.RoommateRomance && owner.friendshipData[npc2.Name].RoommateMarriage))
                    {
                        continue;
                    }

                    if (lastKissTime >= ModEntry.config.MinSpouseKissInterval)
                        kissingSpouses.Clear();


                    float distance = Vector2.Distance(npc1.position, npc2.position);
                    if (
                        npc1.getSpouse() != null && npc2.getSpouse() != null  
                        && npc1.getSpouse().Name == npc2.getSpouse().Name 
                        && distance < ModEntry.config.MaxDistanceToKiss 
                        && !kissingSpouses.Contains(npc1.Name) 
                        && !kissingSpouses.Contains(npc2.Name) 
                        && !npc1.isSleeping 
                        && !npc2.isSleeping 
                        && owner.getFriendshipHeartLevelForNPC(npc1.Name) >= ModEntry.config.MinHeartsForKiss
                        && owner.getFriendshipHeartLevelForNPC(npc2.Name) >= ModEntry.config.MinHeartsForKiss
                        && lastKissTime > ModEntry.config.MinSpouseKissInterval 
                        && ModEntry.myRand.NextDouble() < ModEntry.config.SpouseKissChance
                        && (!ModEntry.config.PreventRelativesFromKissing || !Misc.AreSpousesRelated(npc1.Name, npc2.Name))
                    )
                    {
                        kissingSpouses.Add(npc1.Name);
                        kissingSpouses.Add(npc2.Name);
                        ModEntry.PMonitor.Log("spouses kissing"); 
                        lastKissTime = 0;
                        Vector2 npc1pos = npc1.position;
                        Vector2 npc2pos = npc2.position;
                        int npc1face = npc1.facingDirection;
                        int npc2face = npc1.facingDirection;
                        Vector2 midpoint = new Vector2((npc1.position.X + npc2.position.X) / 2, (npc1.position.Y + npc2.position.Y) / 2);
                        PerformKiss(npc1, midpoint, npc2.Name);
                        PerformKiss(npc2, midpoint, npc1.Name);
                        DelayedAction action = new DelayedAction(1000);
                        var t = Task.Run(async delegate
                        {
                            await Task.Delay(TimeSpan.FromSeconds(1));
                            npc1.position.Value = npc1pos;
                            npc2.position.Value = npc2pos;
                            npc1.FacingDirection = npc1face;
                            npc2.FacingDirection = npc2face;
                            return;
                        });
                    }
                }
            }
        }

19 Source : BoundedExpirationCacheTests.cs
with MIT License
from AElfProject

[Fact]
        public async Task Test_Expiration()
        {
            var hash = HashHelper.ComputeFrom("hello_world");
            var cache = new BoundedExpirationCache(10, 4); // 4ms timeout
            cache.TryAdd(hash);
            await Task.Delay(TimeSpan.FromSeconds(1));

            cache.HasHash(hash, false).ShouldBeTrue();

            cache.HasHash(hash).ShouldBeFalse();
        }

19 Source : BoundedExpirationCacheTests.cs
with MIT License
from AElfProject

[Fact]
        public async Task Test_MultiItem_Expiration()
        {
            int cacheCapacity = 10;
            int timeout = 1_000;
            var cache = new BoundedExpirationCache(cacheCapacity, timeout);
            List<string> hashStrings = new List<string>();
            for (int i = 0; i < cacheCapacity; i++)
            {
                var current = $"hello_world_{i}";
                hashStrings.Add(current);
                cache.TryAdd(HashHelper.ComputeFrom(current)).ShouldBeTrue();
            }
            
            await Task.Delay(TimeSpan.FromMilliseconds(timeout+500));
            
            cache.TryAdd(HashHelper.ComputeFrom($"hello_world_{cacheCapacity}")).ShouldBeTrue();

            foreach (string hashString in hashStrings)
            {
                cache.HasHash(HashHelper.ComputeFrom(hashString)).ShouldBeFalse();
            }
        }

19 Source : FortniteClient.cs
with MIT License
from AeonLucid

public async Task<ProfileResponse> FindPlayerAsync(Platform platform, string epicNickname)
        {
            try
            {
                _queue.WaitOne();

                if (_rateLimitRemaining == 0)
                {
                    var startTime = DateTimeOffset.UtcNow;
                    var difference = _rateLimitResetRemaining - startTime;

                    if (difference > TimeSpan.Zero)
                    {
                        await Task.Delay(difference);
                    }
                    
                    _rateLimitRemaining = RateLimitAmount;
                    _rateLimitResetRemaining = DateTimeOffset.UtcNow + RateLimitDuration;
                }

                var url = Url.Combine("profile", platform.ToString().ToLower(), epicNickname);

                return await url.WithClient(_client).GetJsonAsync<ProfileResponse>();
            }
            finally
            {
                _rateLimitRemaining--;
                _queue.Release();
            }
        }

19 Source : Program.cs
with MIT License
from Aerion

private static async Task<WaitingToken> GetValidWaitingTokenAsync(Client client)
        {
            var waitingToken = await RetryOnFailure(() => client.GetWaitingTokenAsync()).ConfigureAwait(false);
            if (waitingToken.Delay == 0)
            {
                return waitingToken;
            }
            var waitingTokenDelay = TimeSpan.FromSeconds(waitingToken.Delay + 1);

            Console.WriteLine(
                $"Got waiting token, awaiting for {waitingTokenDelay} - until {DateTime.Now.Add(waitingTokenDelay).ToLongTimeString()}");

            await Task.Delay(waitingTokenDelay).ConfigureAwait(false);

            if (waitingToken.Token == null)
            {
                return await GetValidWaitingTokenAsync(client);
            }

            return waitingToken;
        }

19 Source : UploadClient.cs
with MIT License
from agc93

public async Task<bool> CheckStatus(UploadedFile upload)
        {
            var ready = false;
            var attempt = 1;
            do
            {
                await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));
                var json = await _httpClient.GetStringAsync($"/uploads/check_status?id={upload.Id}");
                var resp = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(json);
                var replacedembled = bool.TryParse(resp["file_chunks_rereplacedembled"]?.ToString(), out ready);
            } while (!ready);
            return ready;
        }

19 Source : TriggersTestSuite.cs
with MIT License
from ahydrax

public async Task TriggerTest1()
        {
            var client = new BackgroundJobClient(JobStorage.Current);

            var triggerId = client.OnTriggerSet("trigger-test-1");

            client.ContinueJobWith(triggerId, () => Done());

            await Task.Delay(TimeSpan.FromSeconds(10));

        }

19 Source : RestClient.cs
with MIT License
from Aiko-IT-Systems

private void Handle429(RestResponse response, out Task wait_task, out bool global)
        {
            wait_task = null;
            global = false;

            if (response.Headers == null)
                return;
            var hs = response.Headers;

            // handle the wait
            if (hs.TryGetValue("Retry-After", out var retry_after_raw))
            {
                var retry_after = TimeSpan.FromSeconds(int.Parse(retry_after_raw, CultureInfo.InvariantCulture));
                wait_task = Task.Delay(retry_after);
            }

            // check if global b1nzy
            if (hs.TryGetValue("X-RateLimit-Global", out var isglobal) && isglobal.ToLowerInvariant() == "true")
            {
                // global
                global = true;
            }
        }

19 Source : AsyncEvent.cs
with MIT License
from Aiko-IT-Systems

public async Task InvokeAsync(TSender sender, TArgs e, AsyncEventExceptionMode exceptionMode = AsyncEventExceptionMode.Default)
        {
            var handlers = this._handlers;
            if (handlers.Length == 0)
                return;

            // Collect exceptions
            List<Exception> exceptions = null;
            if ((exceptionMode & AsyncEventExceptionMode.ThrowAll) != 0)
                exceptions = new List<Exception>(handlers.Length * 2 /* timeout + regular */);

            // If we have a timeout configured, start the timeout task
            var timeout = this.MaximumExecutionTime > TimeSpan.Zero ? Task.Delay(this.MaximumExecutionTime) : null;
            for (var i = 0; i < handlers.Length; i++)
            {
                var handler = handlers[i];
                try
                {
                    // Start the handler execution
                    var handlerTask = handler(sender, e);
                    if (handlerTask != null && timeout != null)
                    {
                        // If timeout is configured, wait for any task to finish
                        // If the timeout task finishes first, the handler is causing a timeout

                        var result = await Task.WhenAny(timeout, handlerTask).ConfigureAwait(false);
                        if (result == timeout)
                        {
                            timeout = null;
                            var timeoutEx = new AsyncEventTimeoutException<TSender, TArgs>(this, handler);

                            // Notify about the timeout and complete execution
                            if ((exceptionMode & AsyncEventExceptionMode.HandleNonFatal) == AsyncEventExceptionMode.HandleNonFatal)
                                this.HandleException(timeoutEx, handler, sender, e);

                            if ((exceptionMode & AsyncEventExceptionMode.ThrowNonFatal) == AsyncEventExceptionMode.ThrowNonFatal)
                                exceptions.Add(timeoutEx);

                            await handlerTask.ConfigureAwait(false);
                        }
                    }
                    else if (handlerTask != null)
                    {
                        // No timeout is configured, or timeout already expired, proceed as usual
                        await handlerTask.ConfigureAwait(false);
                    }

                    if (e.Handled)
                        break;
                }
                catch (Exception ex)
                {
                    e.Handled = false;

                    if ((exceptionMode & AsyncEventExceptionMode.HandleFatal) == AsyncEventExceptionMode.HandleFatal)
                        this.HandleException(ex, handler, sender, e);

                    if ((exceptionMode & AsyncEventExceptionMode.ThrowFatal) == AsyncEventExceptionMode.ThrowFatal)
                        exceptions.Add(ex);
                }
            }

            if ((exceptionMode & AsyncEventExceptionMode.ThrowAll) != 0 && exceptions.Count > 0)
                throw new AggregateException("Exceptions were thrown during execution of the event's handlers.", exceptions);
        }

19 Source : ClearLoginLogBackgroundService.cs
with MIT License
from aishang2015

public async Task DoWork()
        {
            while (true)
            {
                // 清理过期的日志
                var setting = _loginSetting.GetCacheData(60 * 60 * 24).FirstOrDefault();
                if (setting != null)
                {
                    var expire = DateTime.Now.AddDays(-setting.SaveTime);
                    await _loginLogDetail.RemoveAsync(d => d.OperateAt < expire);
                }
                await _systemIdenreplacedyDbUnitOfWork.SaveAsync();

                // 一小时清理一次
                await Task.Delay(TimeSpan.FromHours(1));
            }
        }

19 Source : ClearOperateLogBackgroundService.cs
with MIT License
from aishang2015

public async Task DoWork()
        {
            while (true)
            {
                // 清理过期的日志
                var settings = _logSettingCaching.GetCacheData();
                foreach (var setting in settings)
                {
                    var expire = DateTime.Now.AddDays(-setting.SaveTime);
                    await _logDetaiRepository.RemoveAsync(d => d.OperateAt < expire && d.SettingId == setting.Id);
                }
                await _systemIdenreplacedyDbUnitOfWork.SaveAsync();

                // 一小时清理一次
                await Task.Delay(TimeSpan.FromHours(1));
            }
        }

19 Source : RetryableWebSocketConnection.cs
with MIT License
from AiursoftWeb

private async Task PullAndMonitorInThisThread(Func<List<Commit<T>>, Task> onData, Func<string> startPositionFactory, Func<Task> onConnected)
        {
            var exitTask = Task.Run(() => _exitEvent.WaitOne());
            var retryGapSeconds = 1;
            var connectedTime = DateTime.MinValue;
            while (!exitTask.IsCompleted)
            {
                try
                {
                    connectedTime = DateTime.UtcNow;

                    AttemptCount++;

                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AttemptCount)));

                    await base.PullAndMonitor(onData, startPositionFactory, onConnected: () => 
                    {
                        IsConnectionHealthy = true;
                        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsConnectionHealthy)));
                        return onConnected();
                    }, true);
                }
                catch (WebSocketException)
                {
                    IsConnectionHealthy = false;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsConnectionHealthy)));
                    OnReconnecting?.Invoke();
                    if (DateTime.UtcNow - connectedTime > TimeSpan.FromMinutes(1))
                    {
                        // Connection held for one minute. Seems to be a healthy server. Retry soon.
                        retryGapSeconds = 1;
                    }

                    // When retry time finish, or asked to finished.
                    await Task.WhenAny(Task.Delay(TimeSpan.FromSeconds(retryGapSeconds)), exitTask);
                    if (retryGapSeconds < 128)
                    {
                        retryGapSeconds *= 2;
                    }
                }
            }
        }

19 Source : ImmediateScheduler.cs
with Apache License 2.0
from akarnokd

public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
        {
            var diff = dueTime - Now;
            Task.Delay(diff).Wait();
            return action(this, state);
        }

19 Source : ImmediateScheduler.cs
with Apache License 2.0
from akarnokd

public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
        {
            Task.Delay(dueTime).Wait();
            return action(this, state);
        }

19 Source : PlainSinkIntegrationTests.cs
with Apache License 2.0
from akkadotnet

[Fact]
        public async Task PlainSink_should_resume_on_deserialization_errors()
        {
            var callCount = 0;
            Directive Decider(Exception cause)
            {
                callCount++;
                switch (cause)
                {
                    case ProduceException<Null, string> ex when ex.Error.IsSerializationError():
                        return Directive.Resume;
                    default:
                        return Directive.Stop;
                }
            }

            var elementsCount = 10;
            var topic1 = CreateTopic(1);
            var group1 = CreateGroup(1);
            
            var producerSettings = ProducerSettings<Null, string>
                .Create(Sys, null, new FailingSerializer())
                .WithBootstrapServers(Fixture.KafkaServer);
            
            var sourceTask = Source
                .From(new []{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
                .Select(elem => new ProducerRecord<Null, string>(new TopicParreplacedion(topic1, 0), elem.ToString()))
                .RunWith(
                    KafkaProducer.PlainSink(producerSettings).WithAttributes(ActorAttributes.CreateSupervisionStrategy(Decider)), 
                    Materializer);
            
            var timeoutTask = Task.Delay(TimeSpan.FromSeconds(5));
            var completeTask = await Task.WhenAny(sourceTask, timeoutTask);
            if (completeTask == timeoutTask)
                throw new Exception("Producer timed out");

            var settings = CreateConsumerSettings<Null, string>(group1).WithValueDeserializer(new StringDeserializer());
            var probe = KafkaConsumer
                .PlainSource(settings, Subscriptions.replacedignment(new TopicParreplacedion(topic1, 0)))
                .Select(c => c.Value)
                .RunWith(this.SinkProbe<string>(), Materializer);

            probe.Request(elementsCount);
            for (var i = 0; i < 9; i++)
            {
                Log.Info($">>>>>>>>>>> {i}");
                probe.ExpectNext();
            }
            callCount.Should().Be(1);
            probe.Cancel();
        }

19 Source : BugFix240SupervisionStrategy.cs
with Apache License 2.0
from akkadotnet

[Fact]
        public async Task SupervisionStrategy_Decider_on_complex_stream_should_work()
        {
            var topic = CreateTopic(1);
            var group = CreateGroup(1);
            var topicParreplacedion = new TopicParreplacedion(topic, 0);
            var committedTopicParreplacedion = new TopicParreplacedion($"{topic}-done", 0);
            var callCount = 0;

            Directive Decider(Exception cause)
            {
                callCount++;
                return Directive.Resume;
            }

            var committerSettings = CommitterSettings.Create(Sys);
            var consumerSettings = CreateConsumerSettings<string>(group);
            var counter = 0;

            // arrange
            await Source.From(Enumerable.Range(1, 10))
                .Select(elem => new ProducerRecord<Null, string>(topicParreplacedion, elem.ToString()))
                .RunWith(KafkaProducer.PlainSink(ProducerSettings), Materializer);

            // act
            var drainingControl = KafkaConsumer.CommittableSource(consumerSettings, Subscriptions.replacedignment(topicParreplacedion))
                .Via(Flow.Create<CommittableMessage<Null, string>>().Select(x =>
                {
                    counter++;
                    // Exception happened here, fail once, when counter is 5
                    if (counter == 5)
                        throw new Exception("BOOM!");
                    return x;
                }))
                .WithAttributes(Attributes.CreateName("CommitableSource").And(ActorAttributes.CreateSupervisionStrategy(Decider)))
                .Select(c => (c.Record.Topic, c.Record.Message.Value, c.CommitableOffset))
                .SelectAsync(1, async t =>
                {
                    Log.Info($"[{t.Topic}]: {t.Value}");
                    // simulate a request-response call that takes 10ms to complete here
                    await Task.Delay(10);
                    return t;
                })
                .Select(t => ProducerMessage.Single(new ProducerRecord<Null, string>(committedTopicParreplacedion, t.Value),
                    t.CommitableOffset))
                .Via(KafkaProducer.FlexiFlow<Null, string, ICommittableOffset>(ProducerSettings)).WithAttributes(Attributes.CreateName("FlexiFlow"))
                .Select(m => (ICommittable)m.PreplacedThrough)
                .AlsoToMaterialized(Committer.Sink(committerSettings), DrainingControl<NotUsed>.Create)
                .To(Flow.Create<ICommittable>()
                    .Async()
                    .GroupedWithin(1000, TimeSpan.FromSeconds(1))
                    .Select(c => c.Count())
                    .Log("MsgCount").AddAttributes(Attributes.CreateLogLevels(LogLevel.InfoLevel))
                    .To(Sink.Ignore<int>()))
                .Run(Sys.Materializer());

            await Task.Delay(TimeSpan.FromSeconds(5));
            await GuardWithTimeoutAsync(drainingControl.DrainAndShutdown(), TimeSpan.FromSeconds(10));
            
            // There should be only 1 decider call
            callCount.Should().Be(1);

            // replacedert that all of the messages, except for those that failed in the stage, got committed
            var settings = CreateConsumerSettings<Null, string>(group);
            var probe = KafkaConsumer
                .PlainSource(settings, Subscriptions.replacedignment(committedTopicParreplacedion))
                .Select(c => c.Message.Value)
                .RunWith(this.SinkProbe<string>(), Materializer);

            probe.Request(9);
            var messages = new List<string>();
            for (var i = 0; i < 9; ++i)
            {
                var message = probe.RequestNext();
                messages.Add(message);
            }

            // Message "5" is missing because the exception happened downstream of the source and we chose to
            // ignore it in the decider
            messages.Should().BeEquivalentTo(new[] {"1", "2", "3", "4", "6", "7", "8", "9", "10"});
            probe.Cancel();
        }

19 Source : KafkaFixture.cs
with Apache License 2.0
from akkadotnet

public async Task InitializeAsync()
        {
            if (TestsConfiguration.UseExistingDockerContainer)
            {
                // When using existing container, no actions should be performed on startup
                return;
            }
            
            // Load images, if they not exist yet
            await EnsureImageExists(ZookeeperImageName, ZookeeperImageTag);
            await EnsureImageExists(KafkaImageName, KafkaImageTag);

            // Generate random ports for zookeeper and kafka
            var zookeeperPort = ThreadLocalRandom.Current.Next(32000, 33000);
            KafkaPort = ThreadLocalRandom.Current.Next(28000, 29000);
            
            // Make resources cleanup before allocating new containers/networks
            await ResourceCleanup();

            // create the containers
            await CreateContainer(ZookeeperImageName, ZookeeperImageTag, _zookeeperContainerName, zookeeperPort, new Dictionary<string, string>()
            {
                ["ZOOKEEPER_CLIENT_PORT"] = zookeeperPort.ToString(),
                ["ZOOKEEPER_TICK_TIME"] = "2000",
            });
            await CreateContainer(KafkaImageName, KafkaImageTag, _kafkaContainerName, KafkaPort, new Dictionary<string, string>()
            {
                ["KAFKA_BROKER_ID"] = "1",
                ["KAFKA_NUM_PARreplacedIONS"] = KafkaParreplacedions.ToString(),
                ["KAFKA_ZOOKEEPER_CONNECT"] = $"{_zookeeperContainerName}:{zookeeperPort}", // referencing zookeeper container directly in common docker network
                ["KAFKA_LISTENERS"] = $"PLAINTEXT://:{KafkaPort}",
                ["KAFKA_ADVERTISED_LISTENERS"] = $"PLAINTEXT://127.0.0.1:{KafkaPort}",
                ["KAFKA_AUTO_CREATE_TOPICS_ENABLE"] = "true",
                ["KAFKA_DELETE_TOPIC_ENABLE"] = "true",
                ["KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR"] = KafkaReplicationFactor.ToString(),
                ["KAFKA_OPTS"] = "-Djava.net.preferIPv4Stack=True"
            });

            // Setting up network for containers to communicate
            var network = await _client.Networks.CreateNetworkAsync(new NetworksCreateParameters(new NetworkCreate())
            {
                Name = _networkName
            });
            await _client.Networks.ConnectNetworkAsync(network.ID, new NetworkConnectParameters()
            {
                Container = _kafkaContainerName
            });
            await _client.Networks.ConnectNetworkAsync(network.ID, new NetworkConnectParameters()
            {
                Container = _zookeeperContainerName
            });

            // start the containers
            await _client.Containers.StartContainerAsync(_zookeeperContainerName, new ContainerStartParameters());
            await _client.Containers.StartContainerAsync(_kafkaContainerName, new ContainerStartParameters());

            // Provide a 10 second startup delay
            await Task.Delay(TimeSpan.FromSeconds(10));
        }

19 Source : KademliaService.cs
with MIT License
from alethic

protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            var fmt = new KProtobufMessageFormat<KNodeId256>();
            var slf = KNodeId<KNodeId256>.Create();
            var ink = new KInvokerPolicy<KNodeId256>(slf, logger: logger);
            var rtr = new KFixedTableRouter<KNodeId256>(slf, logger: logger);
            var kad = new KEngine<KNodeId256>(rtr, ink, lup, str, logger: logger);
            var lup = new KNodeLookup<KNodeId256>(kad, logger: logger);
            var str = new KInMemoryStore<KNodeId256>(rtr, ink, lup, TimeSpan.FromMinutes(1), logger: logger);
            var pub = new KInMemoryPublisher<KNodeId256>(ink, lup, str, logger: logger);
            var udp = new KUdpProtocol<KNodeId256>(2848441, kad, fmt, KIpEndpoint.Any, logger);
            var mcd = new KUdpMulticastDiscovery<KNodeId256>(2848441, kad, fmt, logger: logger);

            await udp.StartAsync(cancellationToken);
            await str.StartAsync(cancellationToken);
            await pub.StartAsync(cancellationToken);
            await mcd.StartAsync(cancellationToken);
            await kad.StartAsync(cancellationToken);

            while (cancellationToken.IsCancellationRequested == false)
                await Task.Delay(TimeSpan.FromSeconds(1));

            await kad.StopAsync();
            await mcd.StopAsync();
            await pub.StopAsync();
            await str.StopAsync();
            await udp.StopAsync();
        }

19 Source : AppHost.cs
with MIT License
from alethic

public async Task RunAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                Start();

                while (cancellationToken.IsCancellationRequested == false)
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    if (AppServer.IsActivated == false)
                        throw new AppHostException("Application host has unexpectedly stopped.");
                }
            }
            catch (OperationCanceledException)
            {
                // ignore
            }
            finally
            {
                Stop();
            }
        }

19 Source : ApnsClient_Tests.cs
with Apache License 2.0
from alexalok

[Fact]
        public async Task Ensure_Send_Does_Not_Deadlock_When_Sync_Waiting_On_Result_With_Sync_Context()
        {
            var (apns, httpHandlerMock) = BoostrapApnsClient();
            var push = CreateStubPush();

            // This always runs on a theadpool thread and sets single-threaded ctx only for that thread.
            // Thereby, we're guaranteed to not be locked when Task.Delay-ing below if ctx is set before
            // Task.Delay has a chance to capture the current ctx.
            var t = Task.Run(() =>
            {
                var singleThreadedSyncCtx = new AsyncContext().SynchronizationContext;
                SynchronizationContext.SetSynchronizationContext(singleThreadedSyncCtx);
                _ = apns.SendAsync(push).Result;
            });
            await Task.Delay(TimeSpan.FromSeconds(1));
            if (!t.IsCompleted)
                throw new Exception("Code has deadlocked.");
        }

19 Source : ApnsClient_Tests.cs
with Apache License 2.0
from alexalok

[Fact]
        public Task SendAsync_Throws_When_Canceled()
        {
            var (apns, httpHandlerMock) = BoostrapApnsClient(delay:TimeSpan.FromSeconds(10));
            var push = CreateStubPush();
            return replacedert.ThrowsAsync<TaskCanceledException>(async () =>
            {
                var cts = new CancellationTokenSource();
                Task sendTask = apns.SendAsync(push, cts.Token);
                await Task.Delay(TimeSpan.FromMilliseconds(1));
                cts.Cancel();
                await sendTask;
            });
        }

19 Source : MultiLikeControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task DoMultiLike()
        {
            var range = this.GroupContentsControlViewModel.CurrentlySelectedMessages;
            if (range == null)
            {
                return;
            }

            var itemList = (range as ObservableCollection<object>).Cast<MessageControlViewModelBase>().ToList();

            var oldestId = itemList.Min(m => long.Parse(m.Id));
            var newestId = itemList.Max(m => long.Parse(m.Id));

            var loadingControl = new LoadingControlViewModel();
            this.GroupContentsControlViewModel.SmallDialogManager.OpenPopup(loadingControl, Guid.Empty);

            foreach (var message in this.GroupContentsControlViewModel.MessagesSorted)
            {
                var id = long.Parse(message.Id);
                if (id >= oldestId && id <= newestId && message is MessageControlViewModel mcvm)
                {
                    loadingControl.Message = $"Liking Message {mcvm.Message.Text}";
                    await mcvm.LikeMessageAsync();
                    await Task.Delay(this.LikeDelay);
                }
            }

            this.DisableMultiLike();

            this.GroupContentsControlViewModel.SmallDialogManager.ClosePopup();
        }

19 Source : ToastHolderViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task DelayedDismissal(ToastNotificationViewModel toast)
        {
            await Task.Delay(this.AutomaticDismissalTime);
            this.CloseToast(toast);
        }

19 Source : MultiLikeControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task DoMultiLike()
        {
            var range = this.GroupContentsControlViewModel.CurrentlySelectedMessages;
            if (range == null)
            {
                return;
            }

            var itemList = (range as ObservableCollection<object>).Cast<MessageControlViewModelBase>().ToList();

            var oldestId = itemList.Min(m => long.Parse(m.Id));
            var newestId = itemList.Max(m => long.Parse(m.Id));

            var loadingControl = new LoadingControlViewModel();
            this.GroupContentsControlViewModel.PopupManager.PopupDialog = loadingControl;

            foreach (var message in this.GroupContentsControlViewModel.SortedMessages)
            {
                var id = long.Parse(message.Id);
                if (id >= oldestId && id <= newestId && message is MessageControlViewModel mcvm)
                {
                    loadingControl.Message = $"Liking Message {mcvm.Message.Text}";
                    await mcvm.LikeMessageAsync();
                    await Task.Delay(this.LikeDelay);
                }
            }

            this.DisableMultiLike();

            this.GroupContentsControlViewModel.PopupManager.PopupDialog = null;
        }

19 Source : DefaultLogServiceClientTests.cs
with MIT License
from aliyun

[Fact, TestPriority(nameof(TestCreateLogStore))]
        public async Task WaitLogStorePrepared()
        {
            var successCount = 0;

            while (true)
            {
                var shardId = (await this.context.Client.ListShardsAsync(this.context.LogStoreName))
                    .EnsureSuccess()
                    .Result
                    .First()
                    .ShardId;

                var result = await this.context.Client.GetCursorAsync(this.context.LogStoreName, shardId, "begin");
                if (result.IsSuccess)
                {
                    this.output.WriteLine(
                        $"{DateTime.Now} [{successCount}] - LogStore created verify ok, cursor was read, shardId={shardId}, cursor={result.Result.Cursor}.");
                    // Require cotinued success 10 times.
                    if (++successCount >= 10)
                    {
                        return;
                    }
                } else
                {
                    successCount = 0;
                }

                await Task.Delay(TimeSpan.FromSeconds(1));
            }
        }

19 Source : DefaultLogServiceClientBenchmark.cs
with MIT License
from aliyun

private async Task WaitLogStorePrepared()
        {
            var successCount = 0;

            while (true)
            {
                var result = await this.client.GetCursorAsync(this.logstoreName, 0, "begin");
                if (result.IsSuccess)
                {
                    Console.WriteLine(
                        $"// {DateTime.Now} [{successCount}] - LogStore created verify ok, cursor was read, shardId=0, cursor={result.Result.Cursor}.");
                    // Require cotinued success 10 times.
                    if (++successCount >= 10)
                    {
                        Console.WriteLine($"// {DateTime.Now} - LogStore created verify preplaced, replacedumes LogStore has been prepared.");
                        this.cursor = result.Result.Cursor;
                        return;
                    }
                } else
                {
                    Console.WriteLine($"// {DateTime.Now} [{successCount}] - LogStore created verify failed, reset success count.");
                    successCount = 0;
                }

                await Task.Delay(TimeSpan.FromSeconds(1));
            }
        }

See More Examples