Exemple #1
0
    public static async Task MethodAsync()
    {
        TaskExt.Log("B1");
        await SomeClass.SomeAsyncApi().ConfigureAwait(false);

        TaskExt.Log("B2");
    }
        public async Task after_waiting_for_next_step_timeToNextStep_should_be_close_to_stepDuration_in_seconds(int stepDuration)
        {
            var calculator = new AuRaStepCalculator(stepDuration, new Timestamper());
            await TaskExt.DelayAtLeast(calculator.TimeToNextStep);

            calculator.TimeToNextStep.Should().BeCloseTo(TimeSpan.FromSeconds(stepDuration), TimeSpan.FromMilliseconds(100));
        }
Exemple #3
0
        public virtual Task Run(IPEndPoint http, IPEndPoint https, CancellationToken cancelToken)
        {
            var hostBuilder = new WebHostBuilder();

            //        .UseContentRoot(Directory.GetCurrentDirectory())
            ConfigureBuilder(hostBuilder);

            var urls = new List <string>();

            if ((http == null) && (https == null))
            {
                throw new CannotOpenApiPortException("No HTTP or HTTPS ports available");
            }
            if (http != null)
            {
                urls.Add(http.ToHttp());
            }
            if (https != null)
            {
                urls.Add(https.ToHttps());
            }
            hostBuilder.UseUrls(urls.ToArray());
            var webHost = hostBuilder.Build();

            return(TaskExt.StartLongRunningTask(() => webHost.Run(cancelToken), cancelToken));
        }
Exemple #4
0
        public async Task <ResGetServiceRecord> GetServiceRecord(ReqGetServiceRecord req)
        {
            var escapedGt     = req.Gamertag.ToSlug();
            var needsQueueing = await CacheMetaHelpers.NeedsQueueing(_dbClient, $"sr-{escapedGt}");

            if (needsQueueing)
            {
                await _dbClient.SetCacheMeta($"sr-{escapedGt}", "in_progress");

                TaskExt.FireAndForget(() => _sqsClient.SendMessageAsync(new QueueEvent
                {
                    Type    = QueueEventTypes.CacheServiceRecord,
                    Payload = new ServiceRecordPayload {
                        Gamertag = req.Gamertag
                    },
                }));

                throw new BaeException("queued_for_caching");
            }

            // TODO(0xdeafcafe): Clean this shit up 🤮
            var sr = await _dbClient.GetServiceRecord(escapedGt);

            var p1 = Mapper.Map <ServiceRecordResponse>(sr);
            var p2 = Mapper.Map <ResGetServiceRecord>(p1);

            p2.CacheInfo = new CacheInfo(sr.CreatedAt);

            return(p2);
        }
Exemple #5
0
        private async Task ProducerLoop()
        {
            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                BlockHeader parentHeader = _blockTree.Head;
                if (parentHeader == null)
                {
                    if (_logger.IsWarn)
                    {
                        _logger.Warn($"Preparing new block - parent header is null");
                    }
                }
                else if (_sealer.CanSeal(parentHeader.Number + 1, parentHeader.Hash))
                {
                    ProduceNewBlock(parentHeader);
                }

                var timeToNextStep = _auRaStepCalculator.TimeToNextStep;
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Waiting {timeToNextStep} for next AuRa step.");
                }
                await TaskExt.DelayAtLeast(timeToNextStep);
            }
        }
        IEnumerator <Task <AsyncCompletedEventArgs> > FetchOperationAsyncHelper(object state, CancellationToken token, int timeout, Action continuator)
        {
            var tcs = new TaskCompletionSource <AsyncCompletedEventArgs>();
            // prepare the timeout
            CancellationToken newToken;

            if (timeout != Timeout.Infinite)
            {
                var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
                TaskExt.CancelAfterEx(cts, timeout * 1000);
                newToken = cts.Token;
            }
            else
            {
                newToken = token;
            }
            /* handle completion */
            AsyncCompletedEventHandler handler = (sender, args) =>
            {
                if (args.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (args.Error != null)
                {
                    tcs.SetException(args.Error);
                }
                else
                {
                    tcs.SetResult(args);
                }
            };

            this.FetchOperationCompleted += handler;
            try
            {
                using (newToken.Register(() =>
                {
                    try
                    {
                        tcs.SetCanceled();
                    }
                    catch (InvalidOperationException)
                    {
                        /* cancel when already finished, does not matter */
#if DEBUG
                        Tracing.WarningDAL("Canceled async db operation, when it has already completed.");
#endif
                    }
                }, useSynchronizationContext: false))
                {
                    this.StartFetchOperation(state);
                    yield return(tcs.Task.Continuation(continuator));
                }
            }
            finally
            {
                this.FetchOperationCompleted -= handler;
            }
        }
Exemple #7
0
        public async Task <(ServiceRecordResponse serviceRecord, ICacheInfo cacheInfo)> GetServiceRecord(Identity identity)
        {
            var path      = $"players/{identity.Gamertag}/h4/servicerecord";
            var key       = $"halo-4/service-record/{identity.XUIDStr}.json";
            var expire    = TimeSpan.FromMinutes(10);
            var cacheInfo = await fetchCacheInfo(key);

            if (cacheInfo != null && cacheInfo.IsFresh())
            {
                return(await fetchContent <ServiceRecordResponse>(key), cacheInfo);
            }

            var response = await requestWaypointData <External.ServiceRecordResponse>(path, null, key);

            if (response == null && cacheInfo != null)
            {
                return(await fetchContent <ServiceRecordResponse>(key), cacheInfo);
            }

            // Transpile and enrich content
            var finalCacheInfo = new CacheInfo(DateTime.UtcNow, expire);
            var final          = _transpiler.ServiceRecord(response);

            final = await _enricher.ServiceRecord(final, response);

            TaskExt.FireAndForget(() => cacheContent(key, final, finalCacheInfo));

            return(final, finalCacheInfo);
        }
Exemple #8
0
        private async Task StartupUiMode(Func <Task> act)
        {
            try {
                ConfigureUiInstances();
                var dbContextFactory = Container.GetInstance <IDbContextFactory>();
                using (var scope = dbContextFactory.Create()) {
                    await StartupInternal().ConfigureAwait(false);

                    // We dont want the UI action to inherit our ctx..
                    using (dbContextFactory.SuppressAmbientContext())
                        await act().ConfigureAwait(false);
                    await AfterUi().ConfigureAwait(false);

                    await scope.SaveChangesAsync().ConfigureAwait(false);
                }
                BackgroundActions();
                await HandleWaitForBackgroundTasks().ConfigureAwait(false);

                // TODO: call from node?
                var task = TaskExt.StartLongRunningTask(
                    () =>
                    new SIHandler().HandleSingleInstanceCall(Common.Flags.FullStartupParameters.ToList()));
            } catch (SQLiteException ex) {
                MainLog.Logger.FormattedErrorException(ex, "A problem was found with a database");
                var message =
                    $"There appears to be a problem with your database. If the problem persists, you can delete the databases from:\n{Common.Paths.LocalDataPath} and {Common.Paths.DataPath}" +
                    "\nError message: " + ex.Message;
                await
                Container.GetInstance <IDialogManager>()
                .MessageBox(new MessageBoxDialogParams(message, "Sync: A problem was found in your database"))
                .ConfigureAwait(false);

                throw;
            }
        }
        private static async Task LaunchSteamHelper(uint appId, SteamHelperRunner steamH)
        {
            var tcs = new TaskCompletionSource <Unit>();

            using (var cts = new CancellationTokenSource()) {
                var t = TaskExt.StartLongRunningTask(
                    async() => {
                    try {
                        await
                        steamH.RunHelperInternal(cts.Token,
                                                 steamH.GetHelperParameters("interactive", appId)
                                                 .Concat(new[] { "-b", "127.0.0.66:48667" }),
                                                 (process, s) => {
                            if (s.StartsWith("Now listening on:"))
                            {
                                tcs.SetResult(Unit.Value);
                            }
                        }, (proces, s) => { })
                        .ConfigureAwait(false);
                    } catch (Exception ex) {
                        tcs.SetException(ex);
                    } finally {
                        // ReSharper disable once MethodSupportsCancellation
                        using (await _l.LockAsync().ConfigureAwait(false))
                            _isRunning = false;
                    }
                }, cts.Token);
                await tcs.Task;
            }
        }
Exemple #10
0
        ReseponseFutureProcess(CancellationTokenSource cts, double timeout)
        {
            this._id         = Guid.NewGuid().ToString();
            _tcs             = new TaskCompletionSource <T>();
            _cts             = cts;
            this.OutTimeSpan = timeout;
            var name    = this.Id;
            var pidinfo = ProcessRegistry.Instance.TryAdd(name, this);

            Pid = pidinfo.Item1;


            if (!pidinfo.Item2)
            {
                throw new ProcessNameExistException(name);
            }



            if (cts != null)
            {
                TaskExt.Delay(this.OutTimeSpan, cts.Token)
                .ContinueWith(t =>
                {
                    if (!_tcs.Task.IsCompleted)
                    {
                        _tcs.TrySetException(new TimeoutException("请求超时!"));

                        this.Dispose();
                    }
                });
            }

            Task = _tcs.Task;
        }
Exemple #11
0
 private static Task LaunchAppThread() => TaskExt.StartLongRunningTask(async() => {
     await LaunchWithNode().ConfigureAwait(false);
     var entryAssembly = typeof(Entrypoint).GetTypeInfo().Assembly;
     var entryPath     = entryAssembly.Location.ToAbsoluteFilePath().ParentDirectoryPath;
     _bootstrapper     = new ElectronAppBootstrapper(_args, entryPath);
     _bootstrapper.Configure();
     await StartupInternal().ConfigureAwait(false);
 });
Exemple #12
0
 public static IAsyncEnumerable <TValue> Empty <TValue>()
 {
     return(Create(() => Create <TValue>(
                       ct => TaskExt.Return(false, ct),
                       () => { throw new InvalidOperationException(); },
                       () => { })
                   ));
 }
        public async Task step_increases_after_timeToNextStep(int stepDuration)
        {
            var calculator = new AuRaStepCalculator(stepDuration, new Timestamper());
            var step       = calculator.CurrentStep;
            await TaskExt.DelayAtLeast(calculator.TimeToNextStep);

            calculator.CurrentStep.Should().Be(step + 1, calculator.TimeToNextStep.ToString());
        }
Exemple #14
0
 private Task InternalScheduleRepeatedly(int initialDelayMs, int intervalMs, Func <bool> action, CancellationToken token)
 {
     if (initialDelayMs == Timeout.Infinite)
     {
         return(TaskExt.CreateInfiniteTask());
     }
     return(InternalScheduleRepeatedlyAsync(initialDelayMs, intervalMs, action, token));
 }
Exemple #15
0
    public static async Task <int> SomeAsyncApi()
    {
        TaskExt.Log("X1");
        await Task.Delay(1000).WithCompletionLog(step: "X1.5").ConfigureAwait(false);

        TaskExt.Log("X2");
        return(42);
    }
 async void HandleGameSetChanged(Game x)
 {
     _settings.Ready = false;
     _settings.GameOptions.RecentGameSet = x == null ? null : new RecentGameSet(x);
     OnPropertyChanged(nameof(ActiveGame));
     await
     TaskExt.StartLongRunningTask(() => TryActiveGameChanged(x))
     .ConfigureAwait(false);
 }
Exemple #17
0
            public Task <bool> MoveNext(CancellationToken cancellationToken)
            {
                if (_disposed)
                {
                    return(TaskExt.Return(false, CancellationToken.None));
                }

                return(_moveNext(cancellationToken));
            }
 Task RunInstaller() => TaskExt.StartLongRunningTask(() => {
     using (var p = Process.Start(_tmpFile, "-install")) {
         //  /vREINSTALL=ALL /vREINSTALLMODE=vomus /v/qb
         p.WaitForExit();
     }
     if (!IsInstalled())
     {
         throw new InstallationFailed();
     }
 });
Exemple #19
0
 public static IAsyncEnumerable <TResult> Repeat <TResult>(TResult element)
 {
     return(Create(() =>
     {
         return Create(
             ct => TaskExt.Return(true, ct),
             () => element,
             () => { }
             );
     }));
 }
Exemple #20
0
        async Task PerformUnpack()
        {
            _statusRepo.Action = RepoStatus.Unpacking;
            _progress.Reset(RepoStatus.Unpacking);
            await _restarter.TryWithUacFallback(TaskExt.StartLongRunningTask(
                                                    () => Tools.Compression.Unpack(_sourceFile, _destination, true)),
                                                "files").ConfigureAwait(false);

            _progress.Update(null, 100);
            _statusRepo.UpdateProgress(90);
        }
        public override Task Start(uint appId, Uri uri)
        {
            _uri = uri;
            var t2 = TaskExt.StartLongRunningTask(async() => {
                using (var drainer = new Drainer(uri)) {
                    await drainer.Drain().ConfigureAwait(false);
                }
            });

            // TODO: Test the connection?
            return(TaskExt.Default);
        }
Exemple #22
0
        public static IAsyncEnumerable <TValue> Throw <TValue>(Exception exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException("exception");
            }

            return(Create(() => Create <TValue>(
                              ct => TaskExt.Throw <bool>(exception, ct),
                              () => { throw new InvalidOperationException(); },
                              () => { })
                          ));
        }
Exemple #23
0
        /// <summary>
        /// Wait all tasks completition with try|cathc block.
        /// </summary>
        /// <returns>True if thread terminated because of timeout.</returns>
        public async Task <bool> AwaitAllPending(TimeSpan?timeout = null)
        {
            var res = await TaskExt.WhenAll(_pendingTasks, timeout);

            foreach (var t in _pendingTasks)
            {
                if (t.IsCanceled || t.IsCompleted || t.IsFaulted)
                {
                    _pendingTasks.TryRemove(t);
                }
            }
            return(res);
        }
Exemple #24
0
        public virtual Task Run(IPEndPoint http, IPEndPoint https, CancellationToken cancelToken)
        {
            var urls = BuildUrls(http, https);

            var hostBuilder = new WebHostBuilder();

            //        .UseContentRoot(Directory.GetCurrentDirectory())
            ConfigureBuilder(hostBuilder);
            hostBuilder.UseUrls(urls.ToArray());
            var webHost = hostBuilder.Build();

            return(TaskExt.StartLongRunningTask(() => webHost.Run(cancelToken), cancelToken));
        }
Exemple #25
0
 protected override void OnStartup(StartupEventArgs e)
 {
     base.OnStartup(e);
     _bootstrapper = new WpfAppBootstrapper(Environment.GetCommandLineArgs().Skip(1).ToArray(),
                                            Assembly.GetEntryAssembly().Location.ToAbsoluteFilePath().ParentDirectoryPath);
     _bootstrapper.Configure();
     if (_bootstrapper.CommandMode)
     {
         HandleSingleInstance();
     }
     _cmBs = new CMBootstrapper <string>(_bootstrapper);
     TaskExt.StartLongRunningTask(StartupInternal).WaitSpecial();
 }
Exemple #26
0
        public static Task RunningQueue <T>(this BlockingCollection <T> block, int maxThreads, Action <T> act)
        {
            var tasks = Enumerable.Range(1, maxThreads > 0
                    ? maxThreads
                    : 1)
                        .Select(x => TaskExt.StartLongRunningTask(() => {
                foreach (var item in block.GetConsumingEnumerable())
                {
                    act(item);
                }
            }));

            return(Task.WhenAll(tasks));
        }
Exemple #27
0
        private static async Task <int> HandleNative(ISteamSessionLocator locator, bool inclRules,
                                                     List <Tuple <string, string> > filter, Action <ArmaServerInfoModel> act)
        {
            var api = new SteamApi(locator);

            var degreeOfParallelism = inclRules ? 30 : 1;

            using (var bc = new BlockingCollection <ArmaServerInfoModel>()) {
                // TODO: better MT model
                var bcT = TaskExt.StartLongRunningTask(async() => {
                    await Task.WhenAll(Enumerable.Range(1, degreeOfParallelism).Select(_ =>
                                                                                       Task.Run(async() => {
                        foreach (var s in bc.GetConsumingEnumerable())
                        {
                            await UpdateServerInfo(s, api, inclRules).ConfigureAwait(false);
                            act(s);
                        }
                    })
                                                                                       ));
                });
                var c2 = await api.GetServerInfo(locator.Session.AppId, x => {
                    try {
                        var ip        = x.m_NetAdr.GetQueryAddressString().Split(':').First();
                        var ipAddress = IPAddress.Parse(ip);
                        var map       = x.GetMap();
                        var s         = new ArmaServerInfoModel(new IPEndPoint(ipAddress, x.m_NetAdr.GetQueryPort()))
                        {
                            ConnectionEndPoint = new IPEndPoint(ipAddress, x.m_NetAdr.GetConnectionPort()),
                            Name            = x.GetServerName(),
                            Tags            = x.GetGameTags(),
                            Mission         = string.IsNullOrEmpty(map) ? null : x.GetGameDescription(),
                            Map             = map,
                            Ping            = x.m_nPing,
                            MaxPlayers      = x.m_nMaxPlayers,
                            CurrentPlayers  = x.m_nPlayers,
                            RequirePassword = x.m_bPassword,
                            IsVacEnabled    = x.m_bSecure,
                            ServerVersion   = x.m_nServerVersion
                        };
                        bc.Add(s);
                    } catch (Exception ex) {
                        Console.WriteLine(ex);
                    }
                }, filter);

                bc.CompleteAdding();
                await bcT;
                return(c2);
            }
        }
Exemple #28
0
 protected override IEnumerable <Task> ExtraJobs(Func <IMutagenReadStream> streamGetter)
 {
     foreach (var t in base.ExtraJobs(streamGetter))
     {
         yield return(t);
     }
     foreach (var source in EnumExt.GetValues <StringsSource>())
     {
         yield return(TaskExt.Run(DoMultithreading, () =>
         {
             return ProcessStringsFilesIndices(streamGetter, new DirectoryInfo(Path.GetDirectoryName(this.SourcePath)), Language.English, source, ModKey.FromNameAndExtension(Path.GetFileName(this.SourcePath)));
         }));
     }
 }
Exemple #29
0
        private Task InternalScheduleOnce(int initialDelayMs, Action action, CancellationToken token)
        {
            if (initialDelayMs == Timeout.Infinite)
            {
                return(TaskExt.CreateInfiniteTask());
            }
            if (initialDelayMs <= 0)
            {
                action();
                return(TaskExt.CreateCompletedTask());
            }

            return(Task.Delay(initialDelayMs, token).Then(t => action()));
        }
Exemple #30
0
        public static async Task SimpleRunningQueue <T>(this IEnumerable <T> items, int maxThreads,
                                                        Action <BlockingCollection <T> > mainAct, Action <T> act)
        {
            var queue = new ConcurrentQueue <T>(items);

            using (var blockingCollection = new BlockingCollection <T>(queue)) {
                var syncTask    = TaskExt.StartLongRunningTask(() => mainAct(blockingCollection));
                var monitorTask = blockingCollection.RunningQueue(maxThreads, act);

                await syncTask.ConfigureAwait(false);

                blockingCollection.CompleteAdding();
                await monitorTask.ConfigureAwait(false);
            }
        }