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 : DefaultHttpClientFactoryTest.cs
with Apache License 2.0
from aspnet

[Fact]
        public async Task Factory_CleanupCycle_DisposesEligibleHandler()
        {
            // Arrange
            var disposeHandler = new DisposeTrackingHandler();
            Options.Get("github").HttpMessageHandlerBuilderActions.Add(b =>
            {
                b.AdditionalHandlers.Add(disposeHandler);
            });

            var factory = new TestHttpClientFactory(Services, ScopeFactory, LoggerFactory, Options, EmptyFilters)
            {
                EnableExpiryTimer = true,
                EnableCleanupTimer = true,
            };

            var cleanupEntry = await SimulateClientUse_Factory_CleanupCycle_DisposesEligibleHandler(factory);

            // Being pretty conservative here because we want this test to be reliable,
            // and it depends on the GC and timing.
            for (var i = 0; i < 3; i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                if (cleanupEntry.CanDispose)
                {
                    break;
                }

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

            replacedert.True(cleanupEntry.CanDispose, "Cleanup entry disposable");

            // Act
            factory.CleanupTimer_Tick();

            // replacedert
            replacedert.Empty(factory._expiredHandlers);
            replacedert.Equal(1, disposeHandler.DisposeCount);
            replacedert.False(factory.CleanupTimerStarted.IsSet, "Cleanup timer not started");
        }

19 Source : DefaultHttpClientFactoryTest.cs
with Apache License 2.0
from aspnet

[Fact]
        public async Task Factory_CleanupCycle_DisposesLiveHandler()
        {
            // Arrange
            var disposeHandler = new DisposeTrackingHandler();
            Options.Get("github").HttpMessageHandlerBuilderActions.Add(b =>
            {
                b.AdditionalHandlers.Add(disposeHandler);
            });

            var factory = new TestHttpClientFactory(Services, ScopeFactory, LoggerFactory, Options, EmptyFilters)
            {
                EnableExpiryTimer = true,
                EnableCleanupTimer = true,
            };

            var cleanupEntry = await SimulateClientUse_Factory_CleanupCycle_DisposesLiveHandler(factory, disposeHandler);

            // Being pretty conservative here because we want this test to be reliable,
            // and it depends on the GC and timing.
            for (var i = 0; i < 3; i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                if (cleanupEntry.CanDispose)
                {
                    break;
                }

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

            replacedert.True(cleanupEntry.CanDispose, "Cleanup entry disposable");

            // Act - 2
            factory.CleanupTimer_Tick();

            // replacedert
            replacedert.Empty(factory._expiredHandlers);
            replacedert.Equal(1, disposeHandler.DisposeCount);
            replacedert.False(factory.CleanupTimerStarted.IsSet, "Cleanup timer not started");
        }

19 Source : BeatSaver.cs
with MIT License
from Assistant

public async Task Wait()
            {
                await Task.Delay(new TimeSpan(Math.Max(ResetTime.Ticks - DateTime.UtcNow.Ticks, 0)));
            }

19 Source : OrleansClusterClientProvider.cs
with MIT License
from Async-Hub

private static IClusterClient TryToConnect(IHttpContextAccessor httpContextAccessor, 
            IdenreplacedyServer4Info idenreplacedyServer4Info)
        {
            var attempt = 0;
            //var logger = loggerFactory.CreateLogger<OrleansClusterClientProvider>();

            while (true)
            {
                try
                {
                    var client = Build(httpContextAccessor, idenreplacedyServer4Info);
                    client.Connect().Wait();

                    //logger.LogInformation("Client successfully connect to silo host");

                    return client;
                }
                catch (AggregateException ex)
                {
                    if (ex.InnerException is SiloUnavailableException)
                    {
                        attempt++;
                        //logger.LogError(ex, ex.Message);

                        if (attempt > _initializeAttemptsBeforeFailing)
                        {
                            throw;
                        }

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

                    //logger.LogError(ex, ex.Message);
                }
            }
        }

19 Source : Program.cs
with Apache License 2.0
from asynkron

private static async Task Main(string[] args)
        {
            Log.SetLoggerFactory(LoggerFactory.Create(l => l.AddConsole().SetMinimumLevel(LogLevel.Information)));

            var system = new ActorSystem(new ActorSystemConfig()
                .WithDeadLetterThrottleInterval(TimeSpan.FromSeconds(1))
                .WithDeadLetterThrottleCount(3)
            );

            var props = Props.FromFunc(c => Task.CompletedTask);

            //spawn an actor
            var pid = system.Root.Spawn(props);

            //stop it, so that any messages sent to it are delivered to DeadLetter stream
            await system.Root.StopAsync(pid);

            for (var i = 0; i < 1000; i++)
            {
                system.EventStream.Publish(new DeadLetterEvent(pid, i, null));
            }

            await Task.Delay(TimeSpan.FromSeconds(2)); //2 sec is greater than the 1 sec ThrottleInterval trigger

            for (var i = 0; i < 1000; i++)
            {
                system.EventStream.Publish(new DeadLetterEvent(pid, i, null));
            }
        }

19 Source : Program.cs
with Apache License 2.0
from asynkron

public Task ReceiveAsync(IContext context)
        {
            switch (context.Message)
            {
                case Started _:

                    Console.WriteLine("LoopActor - Started");

                    context.Send(context.Self, new LoopParentMessage());

                    break;
                case LoopParentMessage _:

                    _ = SafeTask.Run(async () => {
                            context.Send(context.Parent, new RenameCommand {Name = GeneratePronounceableName(5)});

                            await Task.Delay(TimeSpan.FromMilliseconds(500));

                            context.Send(context.Self, new LoopParentMessage());
                        }
                    );

                    break;
            }

            return Task.CompletedTask;
        }

19 Source : ExponentialBackoffStrategy.cs
with Apache License 2.0
from asynkron

public void HandleFailure(
            ISupervisor supervisor,
            PID child,
            RestartStatistics rs,
            Exception reason,
            object? message
        )
        {
            if (rs.NumberOfFailures(_backoffWindow) == 0) rs.Reset();

            rs.Fail();

            var backoff = rs.FailureCount * (int) _initialBackoff.TotalMilliseconds;
            var noise = _random.Next(500);
            var duration = TimeSpan.FromMilliseconds(backoff + noise);
            Task.Delay(duration).ContinueWith(t => supervisor.RestartChildren(reason, child));
        }

19 Source : Throttle.cs
with Apache License 2.0
from asynkron

public static ShouldThrottle Create(
            int maxEventsInPeriod,
            TimeSpan period,
            Action<int>? throttledCallBack = null
        )
        {
            if (maxEventsInPeriod == 0) return () => Valve.Closed;

            if (period == TimeSpan.Zero || maxEventsInPeriod < 1 || maxEventsInPeriod == int.MaxValue)
                return () => Valve.Open;

            var currentEvents = 0;
            return () => {
                var tries = Interlocked.Increment(ref currentEvents);
                if (tries == 1) StartTimer(throttledCallBack);

                if (tries == maxEventsInPeriod) return Valve.Closing;

                return tries > maxEventsInPeriod ? Valve.Closed : Valve.Open;
            };

            void StartTimer(Action<int>? callBack) => _ = SafeTask.Run(async () => {
                    await Task.Delay(period);
                    var timesCalled = Interlocked.Exchange(ref currentEvents, 0);
                    if (timesCalled > maxEventsInPeriod) callBack?.Invoke(timesCalled - maxEventsInPeriod);
                }
            );
        }

19 Source : EndpointSupervisorStrategy.cs
with Apache License 2.0
from asynkron

public void HandleFailure(
            ISupervisor supervisor,
            PID child,
            RestartStatistics rs,
            Exception reason,
            object? message
        )
        {
            if (ShouldStop(rs))
            {
                Logger.LogError(
                    "[EndpointSupervisor] Stopping connection to address {Address} after retries expired because of {Reason}",
                    _address, reason.GetType().Name
                );
                _cancelFutureRetries.Cancel();
                var terminated = new EndpointTerminatedEvent(_address);
                _system.EventStream.Publish(terminated);
            }
            else
            {
                var backoff = rs.FailureCount * (int) _backoff.TotalMilliseconds;
                var noise = _random.Next(500);
                var duration = TimeSpan.FromMilliseconds(backoff + noise);

                _ = SafeTask.Run(async () => {
                        await Task.Delay(duration);

                        if (reason is RpcException rpc && rpc.StatusCode == StatusCode.Unavailable)
                        {
                            Logger.LogWarning(
                                "[EndpointSupervisor] Restarting {Actor} after {Duration} because endpoint is unavailable",
                                child, duration
                            );
                        }
                        else
                        {
                            Logger.LogWarning(reason,
                                "[EndpointSupervisor] Restarting {Actor} after {Duration} because of {Reason}",
                                child, duration, reason.GetType().Name
                            );
                        }
                   
                        supervisor.RestartChildren(reason, child);
                    }
                    , _cancelFutureRetries.Token
                );
            }
        }

19 Source : RemoteTests.cs
with Apache License 2.0
from asynkron

[Fact, DisplayTestMethodName]
        public async Task CanUnwatchRemoteActor()
        {
            var remoteActor = await SpawnRemoteActor(_fixture.RemoteAddress);
            var localActor1 = await SpawnLocalActorAndWatch(remoteActor);
            var localActor2 = await SpawnLocalActorAndWatch(remoteActor);
            System.Root.Send(localActor2, new Unwatch(remoteActor));
            await Task.Delay(TimeSpan.FromSeconds(3)); // wait for unwatch to propagate...
            System.Root.Stop(remoteActor);

            // localActor1 is still watching so should get notified
            replacedert.True(
                await PollUntilTrue(
                    () =>
                        System.Root.RequestAsync<bool>(
                            localActor1, new TerminatedMessageReceived(_fixture.RemoteAddress, remoteActor.Id),
                            TimeSpan.FromSeconds(5)
                        )
                ),
                "Watching actor did not receive Termination message"
            );

            // localActor2 is NOT watching so should not get notified
            replacedert.False(
                await System.Root.RequestAsync<bool>(
                    localActor2, new TerminatedMessageReceived(_fixture.RemoteAddress, remoteActor.Id),
                    TimeSpan.FromSeconds(5)
                ),
                "Unwatch did not succeed."
            );
        }

19 Source : RemoteTests.cs
with Apache License 2.0
from asynkron

private async Task<bool> PollUntilTrue(Func<Task<bool>> predicate, int attempts, TimeSpan interval)
        {
            var logger = Log.CreateLogger(nameof(PollUntilTrue));
            var attempt = 1;

            while (attempt <= attempts)
            {
                logger.LogInformation($"Attempting replacedertion (attempt {attempt} of {attempts})");

                if (await predicate())
                {
                    logger.LogInformation("Preplaceded!");
                    return true;
                }

                attempt++;
                await Task.Delay(interval);
            }

            return false;
        }

19 Source : SwapManager.cs
with GNU General Public License v3.0
from atomex-me

public Task SwapTimeoutControlAsync(
            CancellationToken cancellationToken = default)
        {
            return Task.Run(async () =>
            {
                try
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        await Task.Delay(SwapTimeoutControlInterval)
                            .ConfigureAwait(false);

                        var swaps = (await _account
                            .GetSwapsAsync()
                            .ConfigureAwait(false))
                            .Where(s => s.IsActive && !s.StateFlags.HasFlag(SwapStateFlags.IsPaymentBroadcast))
                            .ToList();

                        foreach (var swap in swaps)
                        {
                            try
                            {
                                if (IsPaymentDeadlineReached(swap))
                                    await CancelSwapByTimeoutAsync(swap, cancellationToken)
                                        .ConfigureAwait(false);
                            }
                            catch (Exception e)
                            {
                                Log.Error(e, "Swap {@id} restore error", swap.Id);
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    Log.Debug("Swaps timeout control canceled.");
                }
                catch (Exception e)
                {
                    Log.Error(e, "Swaps timeout control error.");
                }

            }, cancellationToken);
        }

19 Source : BinanceRestOrderBooksProvider.cs
with GNU General Public License v3.0
from atomex-me

private async Task Run()
        {
            IsAvailable = true;

            try
            {
                while (!_cts.IsCancellationRequested)
                {
                    foreach (var symbol in _symbols)
                    {
                        var binanceSymbol = Symbols[symbol];

                        var response = await _httpClient
                            .GetAsync($"api/v3/ticker/bookTicker?symbol={binanceSymbol}")
                            .ConfigureAwait(false);

                        var responseContent = await response.Content
                            .ReadreplacedtringAsync()
                            .ConfigureAwait(false);

                        var bookTicker = JsonConvert.DeserializeObject<JObject>(responseContent);
                        var bid = bookTicker["bidPrice"].Value<decimal>();
                        var ask = bookTicker["askPrice"].Value<decimal>();
                        var bidQty = bookTicker["bidQty"].Value<decimal>();
                        var askQty = bookTicker["askQty"].Value<decimal>();

                        if (_orderbooks.TryGetValue(binanceSymbol, out var orderBook))
                        {
                            var topOfBook = orderBook.TopOfBook();

                            if (ask != topOfBook.Ask || bid != topOfBook.Bid)
                            {
                                orderBook.ApplySnapshot(new Snapshot
                                {
                                    Symbol = symbol,
                                    Entries = new List<Entry>
                                    {
                                        new Entry
                                        {
                                            Side          = Side.Buy,
                                            Symbol        = symbol,
                                            Price         = bid,
                                            QtyProfile    = new List<decimal> { bidQty },
                                            TransactionId = 0
                                        },
                                        new Entry
                                        {
                                            Side          = Side.Sell,
                                            Symbol        = symbol,
                                            Price         = ask,
                                            QtyProfile    = new List<decimal> { askQty },
                                            TransactionId = 0
                                        },
                                    },
                                    LastTransactionId = 0
                                });

                                LastUpdateTime = DateTime.Now;
                                OrderBookUpdated?.Invoke(this, new OrderBookEventArgs(orderBook));

                                Log.Debug($"Symbol: {symbol}; Bid: {bid}; Ask: {ask}");
                            }
                        }

                        await Task.Delay(200)
                            .ConfigureAwait(false);
                    }

                    await Task.Delay(_updateInterval)
                        .ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
                Log.Debug("Update task canceled");
            }
            catch (Exception e)
            {
                Log.Error(e, "Update task error");
            }
        }

19 Source : TezosWalletViewModel.cs
with GNU General Public License v3.0
from atomex-me

private void OnDelegateClick()
        {
            var viewModel = new DelegateViewModel(App, DialogViewer, async () =>
            {
                await Task.Delay(TimeSpan.FromSeconds(DelegationCheckIntervalInSec))
                    .ConfigureAwait(false);

                await Application.Current.Dispatcher
                    .InvokeAsync(OnUpdateClick);
            });

            DialogViewer.ShowDialog(
                Dialogs.Delegate,
                viewModel,
                defaultPageId: Pages.Delegate);
        }

19 Source : ConversionConfirmationViewModel.cs
with GNU General Public License v3.0
from atomex-me

private async Task<Error> ConvertAsync()
        {
            try
            {
                var account = App.Account;
                var currencyAccount = account
                    .GetCurrencyAccount<ILegacyCurrencyAccount>(FromCurrency.Name);

                var fromWallets = (await currencyAccount
                    .GetUnspentAddressesAsync(
                        toAddress: null,
                        amount: Amount,
                        fee: 0,
                        feePrice: await FromCurrency.GetDefaultFeePriceAsync(),
                        feeUsagePolicy: FeeUsagePolicy.EstimatedFee,
                        addressUsagePolicy: AddressUsagePolicy.UseMinimalBalanceFirst,
                        transactionType: BlockchainTransactionType.SwapPayment))
                    .ToList();

                foreach (var fromWallet in fromWallets)
                    if (fromWallet.Currency != FromCurrency.Name)
                        fromWallet.Currency = FromCurrency.Name;

                // check balances
                var errors = await BalanceChecker.CheckBalancesAsync(App.Account, fromWallets);

                if (errors.Any())
                    return new Error(Errors.SwapError, GetErrorsDescription(errors));

                if (Amount == 0)
                    return new Error(Errors.SwapError, Resources.CvZeroAmount);

                if (Amount > 0 && !fromWallets.Any())
                    return new Error(Errors.SwapError, Resources.CvInsufficientFunds);

                var symbol = App.SymbolsProvider
                    .GetSymbols(App.Account.Network)
                    .SymbolByCurrencies(FromCurrency, ToCurrency);

                var baseCurrency = App.Account.Currencies.GetByName(symbol.Base);
                var side         = symbol.OrderSideForBuyCurrency(ToCurrency);
                var terminal     = App.Terminal;
                var price        = EstimatedPrice;
                var orderPrice   = EstimatedOrderPrice;

                if (price == 0)
                    return new Error(Errors.NoLiquidity, Resources.CvNoLiquidity);

                var qty = AmountHelper.AmountToQty(side, Amount, price, baseCurrency.DigitsMultiplier);

                if (qty < symbol.MinimumQty)
                {
                    var minimumAmount = AmountHelper.QtyToAmount(side, symbol.MinimumQty, price, FromCurrency.DigitsMultiplier);
                    var message = string.Format(CultureInfo.InvariantCulture, Resources.CvMinimumAllowedQtyWarning, minimumAmount, FromCurrency.Name);

                    return new Error(Errors.SwapError, message);
                }

                var order = new Order
                {
                    Symbol          = symbol.Name,
                    TimeStamp       = DateTime.UtcNow,
                    Price           = orderPrice,
                    Qty             = qty,
                    Side            = side,
                    Type            = OrderType.FillOrKill,
                    FromWallets     = fromWallets.ToList(),
                    MakerNetworkFee = EstimatedMakerNetworkFee
                };

                await order.CreateProofOfPossessionAsync(account);

                terminal.OrderSendAsync(order);

                // wait for swap confirmation
                var timeStamp = DateTime.UtcNow;

                while (DateTime.UtcNow < timeStamp + SwapTimeout)
                {
                    await Task.Delay(SwapCheckInterval);

                    var currentOrder = terminal.Account.GetOrderById(order.ClientOrderId);

                    if (currentOrder == null)
                        continue;

                    if (currentOrder.Status == OrderStatus.Pending)
                        continue;

                    if (currentOrder.Status == OrderStatus.PartiallyFilled || currentOrder.Status == OrderStatus.Filled)
                    {
                        var swap = (await terminal.Account
                            .GetSwapsAsync())
                            .FirstOrDefault(s => s.OrderId == currentOrder.Id);

                        if (swap == null)
                            continue;

                        return null;
                    }

                    if (currentOrder.Status == OrderStatus.Canceled)
                        return new Error(Errors.PriceHasChanged, Resources.SvPriceHasChanged);

                    if (currentOrder.Status == OrderStatus.Rejected)
                        return new Error(Errors.OrderRejected, Resources.SvOrderRejected);
                }

                return new Error(Errors.TimeoutReached, Resources.SvTimeoutReached);
            }
            catch (Exception e)
            {
                Log.Error(e, "Conversion error");
            
                return new Error(Errors.SwapError, Resources.CvConversionError);
            }
        }

19 Source : PageTemplate.cs
with Microsoft Public License
from atrenton

public async void CreateNewPage(object sender, EventArgs e)
        {
            var settings = sender as IPageSettingsModel;
            if (settings == null) return;

            int retryCount = 0, retryLimit = 5;
            Func<OneNote.Window, string[], Task> modalDisplay = null;
            OneNote.Window modalOwner = null;
            string[] modalText = null;

            var latencyFactor = (StorageAccount.IsDefault) ? 1 : 10;
            var delay = TimeSpan.FromMilliseconds(500 * latencyFactor);
            var stopwatch = Stopwatch.StartNew();

            for (; ; ) // BEGIN Retry pattern
            {
                try
                {
                    await CreateNewPageTask(settings).ConfigureAwait(false);
                    break;
                }
                catch (Exception ex)
                {
                    modalOwner = Application.Windows.CurrentWindow;
                    if (Utils.ExceptionHandler.IsTransientError(ex))
                    {
                        if (++retryCount > retryLimit)
                        {
                            Utils.ExceptionHandler.HandleException(ex);
                            modalDisplay =
                                Utils.WinHelper.DisplayWarningAsync;
                            modalText = new[] {
                                "OneNote is busy.",
                                "Please try again in a moment."
                            };
                            break;
                        }
                    }
                    else
                    {
                        Utils.ExceptionHandler.HandleException(ex);
                        var errorMessage = new List<string>
                        {
                            "OneNote API Error",
                            Utils.ExceptionHandler.FormatHResult(ex.HResult)
                        };
                        if (App.IsErrorCode(ex.HResult))
                        {
                            errorMessage.Add(App.ErrorCodeTable[ex.HResult]);
                        }
                        modalDisplay = Utils.WinHelper.DisplayErrorAsync;
                        modalText = errorMessage.ToArray();
                        break;
                    }
                }/* end catch */

                Tracer.WriteWarnLine("Transient error, sleeping {0} ms . . .",
                  delay.TotalMilliseconds);

                await Task.Delay(delay).ConfigureAwait(false);
            }// *END* Retry pattern

            stopwatch.Stop();

            if (modalDisplay != null)
            {
                await modalDisplay(modalOwner, modalText).ConfigureAwait(false);
            }
            else
            {
                Tracer.WriteInfoLine("CreateNewPage elapsed time: {0} ms",
                    stopwatch.ElapsedMilliseconds.ToString("N0"));
            }
        }

19 Source : TaskTimeoutExtensions.cs
with MIT License
from aurelia

public static async Task WithTimeout(this Task task, TimeSpan timeoutDelay, string message)
        {
            if (task == await Task.WhenAny(task, Task.Delay(timeoutDelay)))
            {
                task.Wait(); // Allow any errors to propagate
            }
            else
            {
                throw new TimeoutException(message);
            }
        }

19 Source : TaskTimeoutExtensions.cs
with MIT License
from aurelia

public static async Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeoutDelay, string message)
        {
            if (task == await Task.WhenAny(task, Task.Delay(timeoutDelay)))
            {
                return task.Result;
            }
            else
            {
                throw new TimeoutException(message);
            }
        }

19 Source : TestWorkitems.cs
with Apache License 2.0
from Autodesk-Forge

[Fact]
        [Order(Weight = 3.0)]
        public async void WorkItems_Create()
        {
            using (var testScope = Fixture.StartTestScope())
            {
                var wi = new WorkItem()
                {
                    ActivityId = $"{this.nickname}.{this.act.Id}+latest",
                    Arguments = new Dictionary<string, IArgument>
                    {
                        { "dwg",  new XrefTreeArgument() { Url = "http://download.autodesk.com/us/samplefiles/acad/blocks_and_tables_-_imperial.dwg" } },
                        { "params", new StringArgument() { Value = "{ 'ExtractBlockNames': true, 'ExtractLayerNames' : true }" }},
                        { "token", new StringArgument("IamToken!")},
                        { "results", new XrefTreeArgument { Verb=Verb.Put, Headers = new Dictionary<string, string>() { { "Content-Type", "binary/octet-stream" } }, Url = "https://dasdev-testing.s3.us-west-2.amazonaws.com/sdktest?X-Amz-Expires=89925&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIZLLKUTZMHO46VTQ/20190103/us-west-2/s3/aws4_request&X-Amz-Date=20190103T025815Z&X-Amz-SignedHeaders=content-type;host&X-Amz-Signature=4bfe24c8855360be63c9c5915deba8750cf7724a532ebfb4fe996872f57d3541" } }
                    }
                };

                var resp = await Fixture.DesignAutomationClient.CreateWorkItemAsync(wi);
                replacedert.Equal(Status.Pending, resp.Status);
                while (!resp.Status.IsDone())
                {
                    if (testScope.IsRecording)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(5));
                    }
                    resp = await Fixture.DesignAutomationClient.GetWorkitemStatusAsync(resp.Id);
                }
                replacedert.Equal(Status.Success, resp.Status);
            }
        }

19 Source : TestWorkitems.cs
with Apache License 2.0
from Autodesk-Forge

[Fact]
        [Order(Weight = 3.0)]
        public async void WorkItems_CreateWithStringPayload()
        {
            using (var testScope = Fixture.StartTestScope())
            {
                var activityAlias = $"{this.nickname}.{this.act.Id}+latest";
                var payloadString = string.Format(@"
                {{
                    'activityId' : '{0}',
                    'arguments' : {{
                        'dwg' : {{ 'url' : 'http://download.autodesk.com/us/samplefiles/acad/blocks_and_tables_-_imperial.dwg' }},
                        'params' : {{ 'value' : '{{ \'ExtractBlockNames\': true, \'ExtractLayerNames\' : true }}' }},
                        'token' : 'IamToken!',
                        'results' : 
                        {{ 
                            'url' : 'https://dasdev-testing.s3.us-west-2.amazonaws.com/sdktest?X-Amz-Expires=89925&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIZLLKUTZMHO46VTQ/20190103/us-west-2/s3/aws4_request&X-Amz-Date=20190103T025815Z&X-Amz-SignedHeaders=content-type;host&X-Amz-Signature=4bfe24c8855360be63c9c5915deba8750cf7724a532ebfb4fe996872f57d3541',
                            'verb': 'put',
                            'headers': 
                            {{
                              'Content-Type': 'binary/octet-stream'
                            }}
                        }}
                    }}
                }}", activityAlias);

                var wi = JsonConvert.DeserializeObject<WorkItem>(payloadString);

                var resp = await Fixture.DesignAutomationClient.CreateWorkItemAsync(wi);
                replacedert.Equal(Status.Pending, resp.Status);
                while (!resp.Status.IsDone())
                {
                    if (testScope.IsRecording)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(5));
                    }
                    resp = await Fixture.DesignAutomationClient.GetWorkitemStatusAsync(resp.Id);
                }
                replacedert.Equal(Status.Success, resp.Status);
            }
        }

19 Source : TestForgeAppsApi.cs
with Apache License 2.0
from Autodesk-Forge

[Fact]
        [Order(Weight = 0.0)]
        public async void ForgeApps_Delete()
        {
            using (var scope = Fixture.StartTestScope())
            {
                await this.Fixture.DesignAutomationClient.DeleteForgeAppAsync("me");
                if (scope.IsRecording)
                {
                    await Task.Delay(TimeSpan.FromSeconds(60));
                }
            }
        }

19 Source : CacheImpl.cs
with MIT License
from AvaloniaUI

private async Task PurgeExpiredEntriesAsync(TimeSpan interval)
        {
            while (!_disposed)
            {
                await Task.Delay(interval);
                PurgeExpiredEntries();
            }
        }

19 Source : MarginFadeAnimations.cs
with MIT License
from avestura

public static async Task MarginFadeInAnimationAsync(
            this FrameworkElement element,
            Thickness from,
            Thickness to,
            TimeSpan? duration = null,
            bool useFade = true,
            bool makeVisible = true)
        {
            if (duration == null) duration = new TimeSpan(0, 0, 1);
            await Task.Run(async () =>
            {
                if (element == null) return;
                element.Dispatcher.Invoke(() => element.MarginFadeInAnimation(from, to, duration, useFade, makeVisible));
                await Task.Delay(duration.Value);
            });
        }

19 Source : MarginFadeAnimations.cs
with MIT License
from avestura

public static async Task MarginFadeOutAnimationAsync(
            this FrameworkElement element,
            Thickness from,
            Thickness to,
            TimeSpan? duration = null,
            bool useFade = true,
            bool makeVisible = true)
        {
            if (duration == null) duration = new TimeSpan(0, 0, 1);
            await Task.Run(async () =>
            {
                if (element == null) return;
                element.Dispatcher.Invoke(() => element.MarginFadeOutAnimation(from, to, duration, useFade, makeVisible));
                await Task.Delay(duration.Value);
            });
        }

19 Source : MarginFadeAnimations.cs
with MIT License
from avestura

public static async Task MarginFadeInAnimationAsync(
            this FrameworkElement element,
            Thickness from,
            Thickness to,
            TimeSpan? duration = null,
            bool useFade = true,
            bool makeVisible = true)
        {
            if (duration == null) duration = new TimeSpan(0, 0, 1);
            await Task.Run(async () =>
            {
                if (element == null) return;
                element.Dispatcher.Invoke(() =>
                {
                    element.MarginFadeInAnimation(from, to, duration, useFade, makeVisible);
                });
                await Task.Delay(duration.Value);
            });

        }

19 Source : MarginFadeAnimations.cs
with MIT License
from avestura

public static async Task MarginFadeOutAnimationAsync(
            this FrameworkElement element,
            Thickness from,
            Thickness to,
            TimeSpan? duration = null,
            bool useFade = true,
            bool makeVisible = true)
        {
            if (duration == null) duration = new TimeSpan(0, 0, 1);
            await Task.Run(async () =>
            {
                if (element == null) return;
                element.Dispatcher.Invoke(() =>
                {
                    element.MarginFadeOutAnimation(from, to, duration, useFade, makeVisible);
                });
                await Task.Delay(duration.Value);
            });

        }

19 Source : TimelyMessage.cs
with MIT License
from awaescher

public static void ShowMessage(string message, TimeSpan duration)
		{
			int width = message.Length + 6;
			int height = 5;
			int lines = Label.MeasureLines(message, width);

			var dialog = new Dialog(null, width, height);

			var label = new Label((width - 4 - message.Length) / 2, 0, message);
				dialog.Add(label);

			Task.Delay(duration).ContinueWith(t => dialog.Running = false);
			Application.Run(dialog);
			
		}

19 Source : DeploymentManager.cs
with Apache License 2.0
from Azure-App-Service

private async Task Build(
            ChangeSet changeSet,
            ITracer tracer,
            IDisposable deployStep,
            IRepository repository,
            DeploymentInfoBase deploymentInfo,
            Deploymentreplacedytics deploymentreplacedytics,
            bool fullBuildByDefault)
        {
            if (changeSet == null || String.IsNullOrEmpty(changeSet.Id))
            {
                throw new ArgumentException("The changeSet.Id parameter is null or empty", "changeSet.Id");
            }

            ILogger logger = null;
            IDeploymentStatusFile currentStatus = null;
            string buildTempPath = null;
            string id = changeSet.Id;

            try
            {
                logger = GetLogger(id);
                ILogger innerLogger = logger.Log(Resources.Log_PreparingDeployment, TrimId(id));

                currentStatus = _status.Open(id);
                currentStatus.Complete = false;
                currentStatus.StartTime = DateTime.UtcNow;
                currentStatus.Status = DeployStatus.Building;
                currentStatus.StatusText = String.Format(CultureInfo.CurrentCulture, Resources.Status_BuildingAndDeploying, id);
                currentStatus.Save();

                ISiteBuilder builder = null;

                // Add in per-deploy default settings values based on the details of this deployment
                var perDeploymentDefaults = new Dictionary<string, string> { { SettingsKeys.DoBuildDuringDeployment, fullBuildByDefault.ToString() } };
                var settingsProviders = _settings.SettingsProviders.Concat(
                    new[] { new BasicSettingsProvider(perDeploymentDefaults, SettingsProvidersPriority.PerDeploymentDefault) });

                var perDeploymentSettings = DeploymentSettingsManager.BuildPerDeploymentSettingsManager(repository.RepositoryPath, settingsProviders);

                string delayMaxInStr = perDeploymentSettings.GetValue(SettingsKeys.MaxRandomDelayInSec);
                if (!String.IsNullOrEmpty(delayMaxInStr))
                {
                    int maxDelay;
                    if (!Int32.TryParse(delayMaxInStr, out maxDelay) || maxDelay < 0)
                    {
                        tracer.Trace("Invalid {0} value, expect a positive integer, received {1}", SettingsKeys.MaxRandomDelayInSec, delayMaxInStr);
                    }
                    else
                    {
                        tracer.Trace("{0} is set to {1}s", SettingsKeys.MaxRandomDelayInSec, maxDelay);
                        int gap = _random.Next(maxDelay);
                        using (tracer.Step("Randomization applied to {0}, Start sleeping for {1}s", maxDelay, gap))
                        {
                            logger.Log(Resources.Log_DelayingBeforeDeployment, gap);
                            await Task.Delay(TimeSpan.FromSeconds(gap));
                        }
                    }
                }

                try
                {
                    using (tracer.Step("Determining deployment builder"))
                    {
                        builder = _builderFactory.CreateBuilder(tracer, innerLogger, perDeploymentSettings, repository, deploymentInfo);
                        deploymentreplacedytics.ProjectType = builder.ProjectType;
                        tracer.Trace("Builder is {0}", builder.GetType().Name);
                        KuduEventGenerator.Log()
                            .LogMessage(EventLevel.Informational, string.Empty,
                                $"Using builder {builder.GetType().Name} ProjectType = {deploymentreplacedytics.ProjectType}",
                                string.Empty);
                    }
                }
                catch (Exception ex)
                {
                    // If we get a TargetInvocationException, use the inner exception instead to avoid
                    // useless 'Exception has been thrown by the target of an invocation' messages
                    var targetInvocationException = ex as System.Reflection.TargetInvocationException;
                    if (targetInvocationException != null)
                    {
                        ex = targetInvocationException.InnerException;
                    }

                    _globalLogger.Log(ex);

                    innerLogger.Log(ex);

                    MarkStatusComplete(currentStatus, success: false);

                    FailDeployment(tracer, deployStep, deploymentreplacedytics, ex);

                    return;
                }

                // Create a directory for the script output temporary artifacts
                // Use tick count (in hex) instead of guid to keep the path for getting to long
                buildTempPath = Path.Combine(_environment.TempPath, DateTime.UtcNow.Ticks.ToString("x"));
                FileSystemHelpers.EnsureDirectory(buildTempPath);

                var context = new DeploymentContext
                {
                    NextManifestFilePath = GetDeploymentManifestPath(id),
                    PreviousManifestFilePath = GetActiveDeploymentManifestPath(),
                    IgnoreManifest = deploymentInfo != null && deploymentInfo.CleanupTargetDirectory,
                                                                             // Ignoring the manifest will cause kudusync to delete sub-directories / files
                                                                            // in the destination directory that are not present in the source directory,
                                                                            // without checking the manifest to see if the file was copied over to the destination
                                                                            // during a previous kudusync operation. This effectively performs a clean deployment
                                                                            // from the source to the destination directory
                    Tracer = tracer,
                    Logger = logger,
                    GlobalLogger = _globalLogger,
                    OutputPath = GetOutputPath(deploymentInfo, _environment, perDeploymentSettings),
                    BuildTempPath = buildTempPath,
                    CommitId = id,
                    Message = changeSet.Message
                };

                if (context.PreviousManifestFilePath == null)
                {
                    // this file (/site/firstDeploymentManifest) capture the last active deployment when disconnecting SCM
                    context.PreviousManifestFilePath = Path.Combine(_environment.SiteRootPath, Constants.FirstDeploymentManifestFileName);
                    if (!FileSystemHelpers.FileExists(context.PreviousManifestFilePath))
                    {
                        // In the first deployment we want the wwwroot directory to be cleaned, we do that using a manifest file
                        // That has the expected content of a clean deployment (only one file: hostingstart.html)
                        // This will result in KuduSync cleaning this file.
                        context.PreviousManifestFilePath = Path.Combine(_environment.ScriptPath, Constants.FirstDeploymentManifestFileName);
                    }
                }

                PreDeployment(tracer);

                using (tracer.Step("Building"))
                {
                    try
                    {
                        await builder.Build(context);
                        builder.PostBuild(context);
                        await RestartMainSiteIfNeeded(tracer, logger, deploymentInfo);

                        if (FunctionAppHelper.LooksLikeFunctionApp() && _environment.IsOnLinuxConsumption)
                        {
                            // A Linux consumption function app deployment requires (no matter whether it is oryx build or basic deployment)
                            // 1. packaging the output folder
                            // 2. upload the artifact to user's storage account
                            // 3. reset the container workers after deployment
                            await LinuxConsumptionDeploymentHelper.SetupLinuxConsumptionFunctionAppDeployment(
                                env: _environment,
                                settings: _settings,
                                context: context,
                                shouldSyncTriggers: deploymentInfo.DoSyncTriggers,
                                shouldUpdateWebsiteRunFromPackage: deploymentInfo.OverwriteWebsiteRunFromPackage);
                        }

                        await PostDeploymentHelper.SyncFunctionsTriggers(
                            _environment.RequestId, 
                            new PostDeploymentTraceListener(tracer, logger), 
                            deploymentInfo?.SyncFunctionsTriggersPath);

                        TouchWatchedFileIfNeeded(_settings, deploymentInfo, context);

                        if (_settings.RunFromLocalZip() && deploymentInfo is ArtifactDeploymentInfo)
                        {
                            await PostDeploymentHelper.UpdatePackageName(deploymentInfo as ArtifactDeploymentInfo, _environment, logger);
                        }

                        FinishDeployment(id, deployStep);

                        deploymentreplacedytics.VsProjectId = TryGetVsProjectId(context);
                        deploymentreplacedytics.Result = DeployStatus.Success.ToString();
                    }
                    catch (Exception ex)
                    {
                        MarkStatusComplete(currentStatus, success: false);

                        FailDeployment(tracer, deployStep, deploymentreplacedytics, ex);

                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                FailDeployment(tracer, deployStep, deploymentreplacedytics, ex);
            }
            finally
            {
                // Clean the temp folder up
                CleanBuild(tracer, buildTempPath);
            }
        }

19 Source : LinuxConsumptionDeploymentHelper.cs
with Apache License 2.0
from Azure-App-Service

public static async Task SetupLinuxConsumptionFunctionAppDeployment(
            IEnvironment env,
            IDeploymentSettingsManager settings,
            DeploymentContext context,
            bool shouldSyncTriggers,
            bool shouldUpdateWebsiteRunFromPackage)
        {
            string builtFolder = context.OutputPath;
            string packageFolder = env.ArtifactsPath;
            string packageFileName = OryxBuildConstants.FunctionAppBuildSettings.LinuxConsumptionArtifactName;

            // Indicate the memory limitation on Linux Consumption
            context.Logger.Log($"Linux Consumption plan has a 1.5 GB memory limit on a remote build container.");
            context.Logger.Log($"To check our service limit, please visit https://docs.microsoft.com/en-us/azure/azure-functions/functions-scale#service-limits");

            // Try create a placeholder blob in AzureWebJobsStorage
            CloudBlockBlob blob = await GetPlaceholderBlob(context, settings, shouldUpdateWebsiteRunFromPackage);

            // Package built content from oryx build artifact
            string filePath = PackageArtifactFromFolder(env, settings, context, builtFolder, packageFolder, packageFileName);

            // Log function app dependencies to kusto (requirements.txt, package.json, .csproj)
            await LogDependenciesFile(context.RepositoryPath);

            // Upload from DeploymentsPath
            await UploadLinuxConsumptionFunctionAppBuiltContent(context, blob, filePath);

            // Clean up local built content
            FileSystemHelpers.DeleteDirectoryContentsSafe(context.OutputPath);

            // Change WEBSITE_RUN_FROM_PACKAGE app setting
            if (shouldUpdateWebsiteRunFromPackage)
            {
                await UpdateWebsiteRunFromPackageAppSetting(context, blob);
            }

            // Remove Linux consumption plan functionapp workers for the site
            await RemoveLinuxConsumptionFunctionAppWorkers(context);

            // Invoke a warmup call to the main function site
            if (shouldSyncTriggers)
            {
                await Task.Delay(TimeSpan.FromSeconds(5));
                await FunctionHostSyncTriggersAsync(context);
            }
        }

19 Source : LockExtensions.cs
with Apache License 2.0
from Azure-App-Service

private static async Task<bool> WaitToLockAsync(IOperationLock lockObj, string operationName, TimeSpan timeout)
        {
            var elapsed = TimeSpan.Zero;

            while (!lockObj.Lock(operationName))
            {
                if (elapsed >= timeout)
                {
                    return false;
                }

                await Task.Delay(_sleepInterval);
                elapsed += _sleepInterval;
            }

            return true;
        }

19 Source : LogStreamManager.cs
with Apache License 2.0
from Azure-App-Service

public async Task ProcessRequest(HttpContext context)
        {
            _startTime = DateTime.UtcNow;
            _lastTraceTime = _startTime;

            DisableResponseBuffering(context);
            stopwatch = Stopwatch.StartNew();
            
            // CORE TODO Shutdown detector registration

            // CORE TODO double check on semantics of this (null vs empty etc);
            _filter = context.Request.Query[FilterQueryKey].ToString();

            // CORE TODO parse from path
            // path route as in logstream/{*path} without query strings
            // string routePath = context.Request.RequestContext.RouteData.Values["path"] as string;

            string path;
            string routePath = "";
            //bool enableTrace;

            // trim '/'
            routePath = String.IsNullOrEmpty(routePath) ? routePath : routePath.Trim('/');

            var firstPath = routePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();

            // Ensure mounted logFiles dir 
            string mountedLogFilesDir = Path.Combine(_logPath, routePath);

            FileSystemHelpers.EnsureDirectory(mountedLogFilesDir);

            if (ShouldMonitiorMountedLogsPath(mountedLogFilesDir))
            {
                path = mountedLogFilesDir;
            }
            else
            {
                path = volatileLogsPath;
            }

            context.Response.Headers.Add("Content-Type", "text/event-stream");

            await WriteInitialMessage(context);

            // CORE TODO Get the fsw and keep it in scope here with a using that ends at the end

            lock (_thisLock)
            {
                Initialize(path, context);
            }

            if (_logFiles != null)
            {
                NotifyClientWithLineBreak("Starting Log Tail -n 10 of existing logs ----", context);

                try
                {


                    foreach (string log in _logFiles.Keys)
                    {

                        var reader = new StreamReader(log, Encoding.ASCII);

                        var vfsPath = GetFileVfsPath(log);

                        var printLine = log + " " + (!string.IsNullOrEmpty(vfsPath) ? " (" + vfsPath + ")" : "");

                        NotifyClientWithLineBreak(String.Format(
                                    CultureInfo.CurrentCulture,
                                    printLine,
                                    DateTime.UtcNow.ToString("s"),
                                    System.Environment.NewLine), context);

                        foreach (string logLine in Tail(reader, 10))
                        {
                            await context.Response.WriteAsync(logLine);
                            await context.Response.WriteAsync(System.Environment.NewLine);
                        }
                        await context.Response.WriteAsync(System.Environment.NewLine);
                    }
                }
                catch (Exception)
                {
                    // best effort to get tail logs
                }

                NotifyClientWithLineBreak("Ending Log Tail of existing logs ---", context);
            }
            else
            {
                _tracer.TraceError("LogStream: No pervious logfiles");
            }

            NotifyClientWithLineBreak("Starting Live Log Stream ---", context);

            // CORE TODO diagnostics setting for enabling app logging            

            while (!context.RequestAborted.IsCancellationRequested)
            {
                await Task.Delay(HeartbeatInterval);

                var elapsed = stopwatch.Elapsed;

                if (elapsed >= _timeout)
                {
                    var timeoutMsg = String.Format(
                        CultureInfo.CurrentCulture,
                        Resources.LogStream_Timeout,
                        DateTime.UtcNow.ToString("s"),
                        (int)elapsed.TotalMinutes,
                        System.Environment.NewLine);

                    await context.Response.WriteAsync(timeoutMsg);
                    return;
                }
                else if (elapsed >= HeartbeatInterval)
                {
                    var heartbeatMsg = String.Format(
                        CultureInfo.CurrentCulture,
                        Resources.LogStream_Heartbeat,
                        DateTime.UtcNow.ToString("s"),
                        (int)elapsed.TotalMinutes,
                        System.Environment.NewLine);

                    await context.Response.WriteAsync(heartbeatMsg);
                }
            }
        }

19 Source : DropboxHelper.cs
with Apache License 2.0
from Azure-App-Service

public virtual async Task ProcessFileAsync(HttpClient client, string path, string parent, DateTime lastModifiedUtc, bool useOAuth20)
        {
            int retries = 0;
            while (retries <= MaxRetries)
            {
                try
                {
                    if (useOAuth20)
                    {
                        var request = new HttpRequestMessage(HttpMethod.Post, string.Empty);
                        request.Headers.Add("Dropbox-API-Arg", "{\"path\": \"" + DropboxJsonHeaderEncode(path) + "\"}");
                        using (HttpResponseMessage response = await client.SendAsync(request))
                        {
                            using (Stream stream = await response.EnsureSuccessStatusCode().Content.ReadreplacedtreamAsync())
                            {
                                await SafeWriteFile(parent, path, lastModifiedUtc, stream);
                            }
                        }
                    }
                    else
                    {
                        string requestPath = SandboxFilePath + DropboxPathEncode(path.ToLowerInvariant());
                        using (HttpResponseMessage response = await client.GetAsync(requestPath))
                        {
                            using (Stream stream = await response.EnsureSuccessStatusCode().Content.ReadreplacedtreamAsync())
                            {
                                await SafeWriteFile(parent, path, lastModifiedUtc, stream);
                            }
                        }
                    }

                    if (retries > 0)
                    {
                        // Increment the successful retry count
                        Interlocked.Increment(ref _retriedCount);
                    }
                    // Increment the total success counter
                    Interlocked.Increment(ref _successCount);

                    break;
                }
                catch (Exception ex)
                {
                    if (retries == MaxRetries)
                    {
                        Interlocked.Increment(ref _failedCount);
                        LogError("Get({0}) '{1}' failed with {2}", retries, (useOAuth20 ? DownloadContentApiUri : SandboxFilePath) + path, ex.Message);
                        throw;
                    }
                }

                // First retry is 1s, second retry is 20s replaceduming rate-limit
                await Task.Delay(retries == MaxRetries - 1 ? TimeSpan.FromSeconds(1) : RetryWaitToAvoidRateLimit);
                retries++;
            }
        }

19 Source : OneDriveHelper.cs
with Apache License 2.0
from Azure-App-Service

private async Task<bool> RetryHandler(Func<Task> action)
        {
            int retryCount = 0;
            while (retryCount < MaxRetryCount)
            {
                try
                {
                    await action();
                    return true;
                }
                catch (Exception ex)
                {
                    _tracer.TraceError(ex, "RetryError");
                    retryCount++;
                }

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

            return false;
        }

19 Source : RateLimiter.cs
with Apache License 2.0
from Azure-App-Service

private async Task ThrottleCore()
        {
            _current++;
            if (_current > _limit)
            {
                DateTime now = DateTime.UtcNow;
                TimeSpan ts = now - _last;
                TimeSpan waitDuration = _interval - ts;

                if (waitDuration > TimeSpan.Zero)
                {
                    await Task.Delay(waitDuration);
                    _last = DateTime.UtcNow;
                }
                else
                {
                    _last = now;
                }

                _current = 0;
            }
        }

19 Source : Program.cs
with MIT License
from AzureAD

private async static Task WritePayloadToSyncFileAsync(string lockFile, string protectedFile)
        {
            string pid = Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture);
            string errorFile = protectedFile + $"{pid}.e.txt";
            string pidFIle = Path.Combine(Path.GetDirectoryName(protectedFile), "finished", pid + ".txt");

            Console.WriteLine("Starting process: " + pid);
            CrossPlatLock crossPlatLock = null;
            try
            {
                crossPlatLock = new CrossPlatLock(lockFile);
                using (StreamWriter sw = new StreamWriter(protectedFile, true))
                {
                    await sw.WriteLineAsync($"< {pid} {DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture)}").ConfigureAwait(false);

                    // increase contention by simulating a slow writer
                    await Task.Delay(s_artificialContention).ConfigureAwait(false);

                    await sw.WriteLineAsync($"> {pid} {DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture)}").ConfigureAwait(false);
                    ;
                    Console.WriteLine("Process finished: " + pid);

                }
            }
            catch (Exception e)
            {
                File.WriteAllText(errorFile, e.ToString());
                throw;
            }
            finally
            {
                File.WriteAllText(pidFIle, "done");
                crossPlatLock.Dispose();
            }
        }

19 Source : UtilityTests.cs
with MIT License
from AzureAD

private async Task<string> DelayAndReturn(string test, TimeSpan taskDuration)
        {
            await Task.Delay(taskDuration).ConfigureAwait(false);
            return test;
        }

19 Source : UtilityTests.cs
with MIT License
from AzureAD

[Fact(Skip = "Timing depends on resources of build VM, making the test have little value in a CI job")]
        public async Task Measurements_Tests()
        {
            // measure task with no result
            var taskDuration = TimeSpan.FromMilliseconds(100);
            var epsilon = TimeSpan.FromMilliseconds(30).Ticks;
            var measure = await Task.Delay(taskDuration).Measure().ConfigureAwait(false);
            replacedert.True(Math.Abs(measure.Ticks - taskDuration.Ticks) < epsilon, $"{(measure.Ticks - taskDuration.Ticks) / TimeSpan.TicksPerMillisecond}ms exceeds epsilon of 30ms");
            replacedert.Equal(measure.Ticks * 1000.0, measure.MilliSeconds);

            // measure task with a result
            var test = "test";
            var measureResult = await DelayAndReturn(test, taskDuration).Measure().ConfigureAwait(false);
            replacedert.True(Math.Abs(measureResult.Ticks - taskDuration.Ticks) < epsilon);
            replacedert.Same(test, measureResult.Result);

            // verify that an exception is thrown
            await replacedert.ThrowsAsync<InvalidOperationException>(async () => await Task.Run(() => throw new InvalidOperationException()).Measure().ConfigureAwait(false)).ConfigureAwait(false);
        }

19 Source : ProcessInvoker.Windows.cs
with BSD 3-Clause "New" or "Revised" License
from balbarak

private async Task<bool> SendCtrlSignal(ConsoleCtrlEvent signal, TimeSpan timeout)
        {
            //Trace.Info($"Sending {signal} to process {_proc.Id}.");
            ConsoleCtrlDelegate ctrlEventHandler = new ConsoleCtrlDelegate(ConsoleCtrlHandler);
            try
            {
                if (!FreeConsole())
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                if (!AttachConsole(_proc.Id))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                if (!SetConsoleCtrlHandler(ctrlEventHandler, true))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                if (!GenerateConsoleCtrlEvent(signal, 0))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                //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;
                }
            }
            catch (Exception ex)
            {
                //Trace.Info($"{signal} signal doesn't fire successfully.");
                //Trace.Verbose($"Catch exception during send {signal} event to process {_proc.Id}");
                //Trace.Verbose(ex.ToString());
                return false;
            }
            finally
            {
                FreeConsole();
                SetConsoleCtrlHandler(ctrlEventHandler, false);
            }
        }

19 Source : ProcessInvoker.cs
with BSD 3-Clause "New" or "Revised" License
from balbarak

private void OnProcessExited(object sender, EventArgs e)
        {

            _trace?.Verbose($"Exited process {_proc.Id} with exit code {_proc.ExitCode}");

            if (_streamReadCount != 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);

                });
            }
            else
            {
                _processExitedCompletionSource.TrySetResult(true);
            }
        }

19 Source : ProcessInvoker.Linux.cs
with BSD 3-Clause "New" or "Revised" License
from balbarak

private async Task<bool> SendPosixSignal(PosixSignals 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 : CoopClient_Test.cs
with MIT License
from Bannerlord-Coop-Team

private async Task WaitForTimeout()
        {
            TimeSpan waitedFor = TimeSpan.Zero;
            while (waitedFor < m_DisconnectTimeout + m_FrameTime)
            {
                await Task.Delay(m_FrameTime);
                m_Server.Object.Update(m_FrameTime);
                waitedFor += m_FrameTime;
            }

            // Update the client
            while (m_Client.ClientConnected)
            {
                await Task.Delay(m_FrameTime);
                m_Client.Update(m_DisconnectTimeout);
            }
        }

19 Source : CoopClient_Test.cs
with MIT License
from Bannerlord-Coop-Team

private async Task WaitForClientConnect()
        {
            while (!m_Client.ClientConnected)
            {
                await Task.Delay(m_FrameTime);
                m_Server.Object.Update(m_FrameTime);
                m_Client.Update(m_FrameTime);
            }
        }

19 Source : SaveLoadTest.cs
with MIT License
from Bannerlord-Coop-Team

[Fact]
        public void SaveLoadSystemTest()
        {
            TaskCompletionSource<bool> hostInMap = new TaskCompletionSource<bool>();
            TaskCompletionSource<bool> clientInMap = new TaskCompletionSource<bool>();

            TimeSpan load_timeout = TimeSpan.FromMinutes(5);

            environment.OnRegistrationFinished += (instance) =>
            {
                instance.OnGameStateChanged += (state) => {
                    if (state == GameStates.MainMenuReadyState)
                    {
                        instance.SendCommand("StartCoop");
                    }
                    else if (state == GameStates.MapState)
                    {
                        if(instance == host)
                        {
                            hostInMap.SetResult(true);
                        }
                        else if(instance == client)
                        {
                            clientInMap.SetResult(true);
                        }
                        else
                        {
                            throw new Exception($"{instance} is not host or client");
                        }
                    }
                    else if (!typeof(GameStates)
                    .GetFields(BindingFlags.Public | BindingFlags.Static)
                    .Where(f => f.FieldType == typeof(string))
                        .ToDictionary(f => f.Name,
                            f => (string)f.GetValue(null)).Values.Contains(state))
                    {
                        throw new Exception($"{state} not in GameStates");
                    };
                };

                instance.OnCommandResponse += (response) =>
                {
                    Trace.WriteLine(response);
                };

                instance.OnGameStateChanged += (response) =>
                {
                    Trace.WriteLine(response);
                };
            };

            Task bothInMap = Task.WhenAll(new[] { hostInMap.Task, clientInMap.Task });

            Task.WhenAny(bothInMap, Task.Delay(load_timeout)).Wait();

            Thread.Sleep(TimeSpan.FromSeconds(10));

            host.SendCommand("SaveGame", new string[] { SAVE_NAME });

            TaskCompletionSource<bool> hostInMainMenu = new TaskCompletionSource<bool>();
            TaskCompletionSource<bool> clientInMainMenu = new TaskCompletionSource<bool>();

            TimeSpan save_timeout = TimeSpan.FromMinutes(5);

            host.OnGameStateChanged += (state) =>
            {
                if (state == GameStates.InitialState)
                {
                    hostInMainMenu.SetResult(true);
                }
            };
            
            client.OnGameStateChanged += (state) => {
                if (state == GameStates.InitialState)
                {
                    clientInMainMenu.SetResult(true);
                }
            };

            client.SendCommand("ExitToMainMenu");
            clientInMainMenu.Task.Wait();

            host.SendCommand("ExitToMainMenu");
            Task bothInMainMenu = Task.WhenAll(new[] { hostInMainMenu.Task, clientInMainMenu.Task });

            Task.WhenAny(bothInMainMenu, Task.Delay(save_timeout)).Wait();

            Console.WriteLine("Done");
        }

19 Source : BoardArchiver.cs
with MIT License
from bbepis

private async Task AsyncProxyCall(Func<HttpClientProxy, Task> action)
		{
			await using var client = await ProxyProvider.RentHttpClient();

			var threadWaitTask = Task.Delay(ApiCooldownTimespan);

			try
			{
				await action(client.Object);
			}
			catch (Exception ex)
			{
				Program.Log($"ERROR: Network operation failed, and was unhandled. Inconsistencies may arise in continued use of program\r\n" + ex.ToString());
			}

			await threadWaitTask;
		}

19 Source : Importer.cs
with Apache License 2.0
from bcgov

private async Task<bool> SendItemsAsync(HttpMethod method, string url, IEnumerable<object> items)
        {
            if (_options.Import.Delay > 0)
                Task.Delay(new TimeSpan(0, 0, 0, 0, _options.Import.Delay)).Wait();

            var response = await SendAsync(method, url, items);
            using var stream = await response.Content.ReadreplacedtreamAsync();

            if (response.IsSuccessStatusCode)
            {
                var results = await JsonSerializer.DeserializeAsync<IEnumerable<object>>(stream);
                _logger.LogInformation($"Successfully imported items: {results.Count()}");
                return true;
            }

            if (response.Content.Headers.ContentType == new MediaTypeHeaderValue("application/json"))
            {
                var results = await JsonSerializer.DeserializeAsync<object>(stream);
                var json = JsonSerializer.Serialize(results);
                _logger.LogError($"Import failed: status: {response.StatusCode} Details: {json}");
            }
            else
            {
                var readStream = new StreamReader(stream);
                var error = readStream.ReadToEnd();
                _logger.LogError($"Import failed: status: {response.StatusCode} Details: {error}");
            }

            return false;
        }

19 Source : TestSubscriber.cs
with MIT License
from BEagle1984

[Subscribe]
        [SuppressMessage("ReSharper", "UnusedMember.Local", Justification = Justifications.CalledBySilverback)]
        [SuppressMessage("", "IDE0051", Justification = Justifications.CalledBySilverback)]
        private async Task OnMessageReceived(IMessage message)
        {
            if (Delay > TimeSpan.Zero)
                await Task.Delay(Delay);

            ReceivedMessages.Add(message);

            if (message is not ISilverbackEvent &&
                MustFailCount > FailCount || (FailCondition?.Invoke(message) ?? false))
            {
                FailCount++;
                throw new InvalidOperationException("Test failure");
            }
        }

19 Source : AsyncTestingUtil.cs
with MIT License
from BEagle1984

public static async Task WaitAsync(Func<Task<bool>> breakCondition, TimeSpan? timeout = null)
        {
            timeout ??= TimeSpan.FromSeconds(2);

            for (double i = 0; i < timeout.Value.TotalMilliseconds; i += Interval.TotalMilliseconds)
            {
                try
                {
                    if (await breakCondition())
                        break;
                }
                catch (Exception)
                {
                    // Ignore
                }

                await Task.Delay(Interval);
            }
        }

19 Source : NotificationMessageBuilder.cs
with Apache License 2.0
from beckzhu

public void Delay(TimeSpan delay, Action<INotificationMessage> action)
        {
            Task.Delay(delay).ContinueWith(
                context => action(this.Message),
                TaskScheduler.FromCurrentSynchronizationContext());
        }

19 Source : ScrollViewFocusRenderer.cs
with MIT License
from Berrysoft

async void OnScrollToRequested(object sender, ScrollToRequestedEventArgs e)
        {
            ClearRtlScrollCheck();

            // Adding items into the view while scrolling to the end can cause it to fail, as
            // the items have not actually been laid out and return incorrect scroll position
            // values. The ScrollViewRenderer for Android does something similar by waiting up
            // to 10ms for layout to occur.
            int cycle = 0;
            while (Element != null && !Element.IsInNativeLayout)
            {
                await Task.Delay(TimeSpan.FromMilliseconds(1));
                cycle++;

                if (cycle >= 10)
                    break;
            }

            if (Element == null)
                return;

            double x = e.ScrollX, y = e.ScrollY;

            ScrollToMode mode = e.Mode;
            if (mode == ScrollToMode.Element)
            {
                Point pos = Element.GetScrollPositionForElement((VisualElement)e.Element, e.Position);
                x = pos.X;
                y = pos.Y;
                mode = ScrollToMode.Position;
            }

            if (mode == ScrollToMode.Position)
            {
                Control.ChangeView(x, y, null, !e.ShouldAnimate);
            }
            Element.SendScrollFinished();
        }

19 Source : ActionThrottler.cs
with MIT License
from beto-rodriguez

public async void Call()
        {
            lock (_sync)
            {
#if DEBUG
                Calls++;
#endif

                if (_isWaiting) return;
                _isWaiting = true;
            }

            await Task.Delay(ThrottlerTimeSpan);

            // notice it is important that the unlock comes before invoking the Action
            // this way we can call the throttler again from the Action
            // otherwise calling the throttler from the Action will be ignored always.
            lock (_sync)
            {
                _isWaiting = false;
            }

            await _action();
        }

See More Examples