System.Threading.Tasks.Task.ConfigureAwait(bool)

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

18404 Examples 7

19 View Source File : DocumentApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public virtual async Task<PatchDoreplacedentResponse<U>> PatchDoreplacedentAsync<T, U>(
            string collectionName,
            string doreplacedentKey,
            T body,
            PatchDoreplacedentQuery query = null,
            DoreplacedentHeaderProperties headers = null)
        {
            string doreplacedentHandle = WebUtility.UrlEncode(collectionName) +
                "/" + WebUtility.UrlEncode(doreplacedentKey);

            return await PatchDoreplacedentAsync<T, U>(doreplacedentHandle, body, query, headers: headers).ConfigureAwait(false);
        }

19 View Source File : FileContainerHttpClient.cs
License : MIT License
Project Creator : actions

private async Task<Stream> DownloadAsync(
            Int64 containerId,
            String itemPath,
            String contentType,
            CancellationToken cancellationToken,
            Guid scopeIdentifier,
            Object userState = null)
        {
            HttpResponseMessage response = await ContainerGetRequestAsync(containerId, itemPath, contentType, cancellationToken, scopeIdentifier, userState).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();

            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                throw new ContainerNoContentException();
            }

            if (VssStringComparer.ContentType.Equals(response.Content.Headers.ContentType.MediaType, contentType))
            {
                if (response.Content.Headers.ContentEncoding.Contains("gzip", StringComparer.OrdinalIgnoreCase))
                {
                    return new GZipStream(await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false), CompressionMode.Decompress);
                }
                else
                {
                    return await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
                }
            }
            else
            {
                throw new ContainerUnexpectedContentTypeException(contentType, response.Content.Headers.ContentType.MediaType);
            }
        }

19 View Source File : RecordFSRepo.cs
License : Apache License 2.0
Project Creator : acblog

public override async Task<T?> Get(string id, CancellationToken cancellationToken = default)
        {
            string path = GetPath(id);
            await using var fs = System.IO.File.OpenRead(path);
            using var sr = new StreamReader(fs);
            var src = await sr.ReadToEndAsync().ConfigureAwait(false);
            var (metadata, content) = ObjectTextual.Parse<TMeta>(src);

            return await CreateExistedItem(id, metadata, content).ConfigureAwait(false);
        }

19 View Source File : DocumentApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public virtual async Task<DeleteDoreplacedentResponse<object>> DeleteDoreplacedentAsync(
            string collectionName,
            string doreplacedentKey,
            DeleteDoreplacedentQuery query = null,
            DoreplacedentHeaderProperties headers = null)
        {
            return await DeleteDoreplacedentAsync<object>(
                $"{WebUtility.UrlEncode(collectionName)}/{WebUtility.UrlEncode(doreplacedentKey)}",
                query, headers).ConfigureAwait(false);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : acid-chicken

public static async Task SaveBotConfigAsync()
        {
        //  ApplicationConfig.Monitors = MonitorManager.Targets.Zip(MonitorManager.Statuses, (x, y) => new KeyValuePair<string, Monitor>(x.Key, new Monitor(x.Value, y.Value))).ToDictionary(x => x.Key, x => x.Value);
            await SaveConfigAsync(ApplicationConfig).ConfigureAwait(false);
        }

19 View Source File : PostRepositoryBuilder.cs
License : Apache License 2.0
Project Creator : acblog

public override async Task Build(IList<Post> data)
        {
            data = (from x in data orderby x.CreationTime descending select x).ToArray();
            await base.Build(data).ConfigureAwait(false);
            await BuildIndexType(data).ConfigureAwait(false);
            await BuildIndexKeyword(data).ConfigureAwait(false);
            await BuildIndexCategory(data).ConfigureAwait(false);
        }

19 View Source File : VssHttpMessageHandler.cs
License : MIT License
Project Creator : actions

protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            VssTraceActivity traceActivity = VssTraceActivity.Current;

            var traceInfo = VssHttpMessageHandlerTraceInfo.GetTraceInfo(request);
            traceInfo?.TraceHandlerStartTime();

            if (!m_appliedClientCertificatesToTransportHandler &&
                request.RequestUri.Scheme == "https")
            {
                HttpClientHandler httpClientHandler = m_transportHandler as HttpClientHandler;
                if (httpClientHandler != null &&
                    this.Settings.ClientCertificateManager != null &&
                    this.Settings.ClientCertificateManager.ClientCertificates != null &&
                    this.Settings.ClientCertificateManager.ClientCertificates.Count > 0)
                {
                    httpClientHandler.ClientCertificates.AddRange(this.Settings.ClientCertificateManager.ClientCertificates);
                }
                m_appliedClientCertificatesToTransportHandler = true;
            }

            if (!m_appliedServerCertificateValidationCallbackToTransportHandler &&
                request.RequestUri.Scheme == "https")
            {
                HttpClientHandler httpClientHandler = m_transportHandler as HttpClientHandler;
                if (httpClientHandler != null &&
                    this.Settings.ServerCertificateValidationCallback != null)
                {
                    httpClientHandler.ServerCertificateCustomValidationCallback = this.Settings.ServerCertificateValidationCallback;
                }
                m_appliedServerCertificateValidationCallbackToTransportHandler = true;
            }

            // The .NET Core 2.1 runtime switched its HTTP default from HTTP 1.1 to HTTP 2.
            // This causes problems with some versions of the Curl handler on Linux.
            // See GitHub issue https://github.com/dotnet/corefx/issues/32376
            if (Settings.UseHttp11)
            {
                request.Version = HttpVersion.Version11;
            }

            IssuedToken token = null;
            IssuedTokenProvider provider;
            if (this.Credentials.TryGetTokenProvider(request.RequestUri, out provider))
            {
                token = provider.CurrentToken;
            }

            // Add ourselves to the message so the underlying token issuers may use it if necessary
            request.Properties[VssHttpMessageHandler.PropertyName] = this;

            Boolean succeeded = false;
            Boolean lastResponseDemandedProxyAuth = false;
            Int32 retries = m_maxAuthRetries;
            HttpResponseMessage response = null;
            HttpResponseMessageWrapper responseWrapper;
            CancellationTokenSource tokenSource = null;

            try
            {
                tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

                if (this.Settings.SendTimeout > TimeSpan.Zero)
                {
                    tokenSource.CancelAfter(this.Settings.SendTimeout);
                }

                do
                {
                    if (response != null)
                    {
                        response.Dispose();
                    }

                    ApplyHeaders(request);

                    // In the case of a Windows token, only apply it to the web proxy if it
                    // returned a 407 Proxy Authentication Required. If we didn't get this
                    // status code back, then the proxy (if there is one) is clearly working fine,
                    // so we shouldn't mess with its credentials.
                    ApplyToken(request, token, applyICredentialsToWebProxy: lastResponseDemandedProxyAuth);
                    lastResponseDemandedProxyAuth = false;

                    // The WinHttpHandler will chunk any content that does not have a computed length which is
                    // not what we want. By loading into a buffer up-front we bypreplaced this behavior and there is
                    // no difference in the normal HttpClientHandler behavior here since this is what they were
                    // already doing.
                    await BufferRequestContentAsync(request, tokenSource.Token).ConfigureAwait(false);

                    traceInfo?.TraceBufferedRequestTime();

                    // ConfigureAwait(false) enables the continuation to be run outside any captured 
                    // SyncronizationContext (such as ASP.NET's) which keeps things from deadlocking...
                    response = await m_messageInvoker.SendAsync(request, tokenSource.Token).ConfigureAwait(false);

                    traceInfo?.TraceRequestSendTime();

                    // Now buffer the response content if configured to do so. In general we will be buffering
                    // the response content in this location, except in the few cases where the caller has 
                    // specified HttpCompletionOption.ResponseHeadersRead.
                    // Trace content type in case of error
                    await BufferResponseContentAsync(request, response, () => $"[ContentType: {response.Content.GetType().Name}]", tokenSource.Token).ConfigureAwait(false);

                    traceInfo?.TraceResponseContentTime();

                    responseWrapper = new HttpResponseMessageWrapper(response);

                    if (!this.Credentials.IsAuthenticationChallenge(responseWrapper))
                    {
                        // Validate the token after it has been successfully authenticated with the server.
                        if (provider != null)
                        {
                            provider.ValidateToken(token, responseWrapper);
                        }

                        // Make sure that once we can authenticate with the service that we turn off the 
                        // Expect100Continue behavior to increase performance.
                        this.ExpectContinue = false;
                        succeeded = true;
                        break;
                    }
                    else
                    {
                        // In the case of a Windows token, only apply it to the web proxy if it
                        // returned a 407 Proxy Authentication Required. If we didn't get this
                        // status code back, then the proxy (if there is one) is clearly working fine,
                        // so we shouldn't mess with its credentials.
                        lastResponseDemandedProxyAuth = responseWrapper.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;

                        // Invalidate the token and ensure that we have the correct token provider for the challenge
                        // which we just received
                        VssHttpEventSource.Log.AuthenticationFailed(traceActivity, response);

                        if (provider != null)
                        {
                            provider.InvalidateToken(token);
                        }

                        // Ensure we have an appropriate token provider for the current challenge
                        provider = this.Credentials.CreateTokenProvider(request.RequestUri, responseWrapper, token);

                        // Make sure we don't invoke the provider in an invalid state
                        if (provider == null)
                        {
                            VssHttpEventSource.Log.IssuedTokenProviderNotFound(traceActivity);
                            break;
                        }
                        else if (provider.GetTokenIsInteractive && this.Credentials.PromptType == CredentialPromptType.DoNotPrompt)
                        {
                            VssHttpEventSource.Log.IssuedTokenProviderPromptRequired(traceActivity, provider);
                            break;
                        }

                        // If the user has already tried once but still unauthorized, stop retrying. The main scenario for this condition
                        // is a user typed in a valid credentials for a hosted account but the replacedociated idenreplacedy does not have 
                        // access. We do not want to continually prompt 3 times without telling them the failure reason. In the 
                        // next release we should rethink about presenting user the failure and options between retries.
                        IEnumerable<String> headerValues;
                        Boolean hasAuthenticateError =
                            response.Headers.TryGetValues(HttpHeaders.VssAuthenticateError, out headerValues) &&
                            !String.IsNullOrEmpty(headerValues.FirstOrDefault());

                        if (retries == 0 || (retries < m_maxAuthRetries && hasAuthenticateError))
                        {
                            break;
                        }

                        // Now invoke the provider and await the result
                        token = await provider.GetTokenAsync(token, tokenSource.Token).ConfigureAwait(false);

                        // I always see 0 here, but the method above could take more time so keep for now
                        traceInfo?.TraceGetTokenTime();

                        // If we just received a token, lets ask the server for the VSID
                        request.Headers.Add(HttpHeaders.VssUserData, String.Empty);

                        retries--;
                    }
                }
                while (retries >= 0);

                if (traceInfo != null)
                {
                    traceInfo.TokenRetries = m_maxAuthRetries - retries;
                }

                // We're out of retries and the response was an auth challenge -- then the request was unauthorized
                // and we will throw a strongly-typed exception with a friendly error message.
                if (!succeeded && response != null && this.Credentials.IsAuthenticationChallenge(responseWrapper))
                {
                    String message = null;
                    IEnumerable<String> serviceError;

                    if (response.Headers.TryGetValues(HttpHeaders.TfsServiceError, out serviceError))
                    {
                        message = UriUtility.UrlDecode(serviceError.FirstOrDefault());
                    }
                    else
                    {
                        message = CommonResources.VssUnauthorized(request.RequestUri.GetLeftPart(UriPartial.Authority));
                    }

                    // Make sure we do not leak the response object when raising an exception
                    if (response != null)
                    {
                        response.Dispose();
                    }

                    VssHttpEventSource.Log.HttpRequestUnauthorized(traceActivity, request, message);
                    VssUnauthorizedException unauthorizedException = new VssUnauthorizedException(message);

                    if (provider != null)
                    {
                        unauthorizedException.Data.Add(CredentialsType, provider.CredentialType);
                    }

                    throw unauthorizedException;
                }

                return response;
            }
            catch (OperationCanceledException ex)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    VssHttpEventSource.Log.HttpRequestCancelled(traceActivity, request);
                    throw;
                }
                else
                {
                    VssHttpEventSource.Log.HttpRequestTimedOut(traceActivity, request, this.Settings.SendTimeout);
                    throw new TimeoutException(CommonResources.HttpRequestTimeout(this.Settings.SendTimeout), ex);
                }
            }
            finally
            {
                // We always dispose of the token source since otherwise we leak resources if there is a timer pending
                if (tokenSource != null)
                {
                    tokenSource.Dispose();
                }

                traceInfo?.TraceTrailingTime();
            }
        }

19 View Source File : DiscordRPforVSPackage.cs
License : GNU Affero General Public License v3.0
Project Creator : 1thenikita

[System.Diagnostics.Codereplacedysis.SuppressMessage("Usage", "VSTHRD100:Avoid async void methods")]
        private async void WindowActivated(Window windowActivated, Window lastWindow)
        {
            await this.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                if (!this.Discord.Initialize())
                    ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");

            if (windowActivated.Doreplacedent != null)
                await this.UpdatePresenceAsync(windowActivated.Doreplacedent).ConfigureAwait(true);
        }

19 View Source File : TaskCancellationExtensions.cs
License : MIT License
Project Creator : actions

public static Task EnforceCancellation(
            this Task task,
            CancellationToken cancellationToken,
            Func<string> makeMessage = null,
            [CallerFilePath] string file = "",
            [CallerMemberName] string member = "",
            [CallerLineNumber] int line = -1)
        {
            Func<Task<Void>> task2 = async () =>
            {
                await task.ConfigureAwait(false);
                return new Void();
            };

            return task2().EnforceCancellation<Void>(cancellationToken, makeMessage, file, member, line);
        }

19 View Source File : StringIntoFileInjector.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<string> GetInjectedHtmlFileAsync(string fileName, params string[] strings)
        {

            var mainDir = AppDomain.CurrentDomain.BaseDirectory;
            var appCode = Path.Combine(mainDir, "Injectables");
            var requiredFile = Path.Combine(appCode, fileName);

            using (StreamReader reader = new StreamReader(requiredFile))
            {
                var content = await reader.ReadToEndAsync().ConfigureAwait(false);
                var injectedContent = string.Format(content, strings);
                return injectedContent;
            }
        }

19 View Source File : CursorApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public virtual async Task<CursorResponse<T>> PostCursorAsync<T>(
                string query,
                Dictionary<string, object> bindVars = null,
                PostCursorOptions options = null,
                bool? count = null,
                long? batchSize = null,
                bool? cache = null,
                long? memoryLimit = null,
                int? ttl = null,
                string transactionId = null)
        {
            var headerProperties = new CursorHeaderProperties();
            if (!string.IsNullOrWhiteSpace(transactionId))
            {
                headerProperties.TransactionId = transactionId;
            }

            return await PostCursorAsync<T>(
                new PostCursorBody
                {
                    Query = query,
                    BindVars = bindVars,
                    Options = options,
                    Count = count,
                    BatchSize = batchSize,
                    Cache = cache,
                    MemoryLimit = memoryLimit,
                    Ttl = ttl
                }, headerProperties).ConfigureAwait(false);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : acid-chicken

public static async Task LogAsync(LogMessage message)
        {
            while (IsLoggerLocked)
            {
                await Task.Delay(1).ConfigureAwait(false);
            }
            IsLoggerLocked = true;
            switch (message.Severity)
            {
                case LogSeverity.Critical:
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    break;
                case LogSeverity.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
                case LogSeverity.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;
                case LogSeverity.Info:
                    Console.ForegroundColor = ConsoleColor.Green;
                    break;
                case LogSeverity.Verbose:
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    break;
                case LogSeverity.Debug:
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    break;
            }
            await Console.Out.WriteLineAsync($"[{message.Source}]{message.Message}").ConfigureAwait(false);
            Console.ResetColor();
            IsLoggerLocked = false;
        }

19 View Source File : ListatStatisticRepository.cs
License : Apache License 2.0
Project Creator : acblog

public async Task<bool> Exists(string id, CancellationToken cancellationToken = default)
        {
            try
            {
                var result = await Get(id, cancellationToken).ConfigureAwait(false);
                return result is not null;
            }
            catch
            {
                return false;
            }
        }

19 View Source File : DocumentApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public virtual async Task<DeleteDoreplacedentResponse<T>> DeleteDoreplacedentAsync<T>(
            string collectionName,
            string doreplacedentKey,
            DeleteDoreplacedentQuery query = null,
            DoreplacedentHeaderProperties headers = null)
        {
            return await DeleteDoreplacedentAsync<T>(
                $"{WebUtility.UrlEncode(collectionName)}/{WebUtility.UrlEncode(doreplacedentKey)}",
                query, headers).ConfigureAwait(false);
        }

19 View Source File : DiscordRPforVSPackage.cs
License : GNU Affero General Public License v3.0
Project Creator : 1thenikita

protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
        {
            try
            {
                await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
                Settings.Upgrade();

                // Writes the language used to the global variable
                Settings.translates = Settings.Default.useEnglishLanguage ? "en-US" : CultureInfo.CurrentCulture.ToString();
                Settings.Default.Save();

                ide = GetGlobalService(typeof(SDTE)) as DTE;
                ide.Events.WindowEvents.WindowActivated += this.WindowActivated;
                ide.Events.SolutionEvents.BeforeClosing += this.SolutionBeforeClosing;

                String ideVersion = ide.Version.Split(new Char[1] { '.' })[0];
                this.versionString = $"Visual Studio {Constants.IdeVersions[Int32.Parse(ideVersion, CultureInfo.InvariantCulture)]}";
                this.versionImageKey = $"dev{ideVersion}";

                await SettingsCommand.InitializeAsync(this).ConfigureAwait(true);

                if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                    if (!this.Discord.Initialize())
                        ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");

                if (Settings.loadOnStartup)
                    await this.UpdatePresenceAsync(ide.ActiveDoreplacedent).ConfigureAwait(true);

                await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true);
            }
            catch (OperationCanceledException exc)
            {
                ActivityLog.LogError(exc.Source, exc.Message);
            }
        }

19 View Source File : ThrottlingReportHandler.cs
License : MIT License
Project Creator : actions

protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Call the inner handler.
            var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

            // Inspect whether response has throttling information
            IEnumerable<string> vssRequestDelayed = null;
            IEnumerable<string> vssRequestQuotaReset = null;

            if (response.Headers.TryGetValues(HttpHeaders.VssRateLimitDelay, out vssRequestDelayed) &&
                response.Headers.TryGetValues(HttpHeaders.VssRateLimitReset, out vssRequestQuotaReset) &&
                !string.IsNullOrEmpty(vssRequestDelayed.FirstOrDefault()) &&
                !string.IsNullOrEmpty(vssRequestQuotaReset.FirstOrDefault()))
            {
                TimeSpan delay = TimeSpan.FromSeconds(double.Parse(vssRequestDelayed.First()));
                int expirationEpoch = int.Parse(vssRequestQuotaReset.First());
                DateTime expiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expirationEpoch);

                _throttlingReporter.ReportThrottling(delay, expiration);
            }

            return response;
        }

19 View Source File : RecordFSBuilderBase.cs
License : Apache License 2.0
Project Creator : acblog

public virtual async Task Build(IList<T> data)
        {
            FSStaticBuilder.EnsureDirectoryEmpty(RootPath);
            FSStaticBuilder.EnsureDirectoryEmpty(Paths.GetDataRoot(RootPath));
            FSStaticBuilder.EnsureDirectoryEmpty(Paths.GetConfigRoot(RootPath));
            FSStaticBuilder.EnsureDirectoryEmpty(Paths.GetIndexRoot(RootPath));

            await BuildData(data).ConfigureAwait(false);
        }

19 View Source File : VssHttpRetryMessageHandler.cs
License : MIT License
Project Creator : actions

protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            Int32 attempt = 1;
            HttpResponseMessage response = null;
            HttpRequestException exception = null;
            VssTraceActivity traceActivity = VssTraceActivity.Current;

            // Allow overriding default retry options per request
            VssHttpRetryOptions retryOptions = m_retryOptions;
            object retryOptionsObject;
            if (request.Properties.TryGetValue(HttpRetryOptionsKey, out retryOptionsObject)) // NETSTANDARD compliant, TryGetValue<T> is not
            {
                // Fallback to default options if object of unexpected type was preplaceded
                retryOptions = retryOptionsObject as VssHttpRetryOptions ?? m_retryOptions;
            }

            TimeSpan minBackoff = retryOptions.MinBackoff;
            Int32 maxAttempts = retryOptions.MaxRetries + 1;

            IVssHttpRetryInfo retryInfo = null;
            object retryInfoObject;
            if (request.Properties.TryGetValue(HttpRetryInfoKey, out retryInfoObject)) // NETSTANDARD compliant, TryGetValue<T> is not
            {
                retryInfo = retryInfoObject as IVssHttpRetryInfo;
            }

            if (IsLowPriority(request))
            {
                // Increase the backoff and retry count, low priority requests can be retried many times if the server is busy.
                minBackoff = TimeSpan.FromSeconds(minBackoff.TotalSeconds * 2);
                maxAttempts = maxAttempts * 10;
            }

            TimeSpan backoff = minBackoff;

            while (attempt <= maxAttempts)
            {
                // Reset the exception so we don't have a lingering variable
                exception = null;

                Boolean canRetry = false;
                SocketError? socketError = null;
                HttpStatusCode? statusCode = null;
                WebExceptionStatus? webExceptionStatus = null;
                WinHttpErrorCode? winHttpErrorCode = null;
                CurlErrorCode? curlErrorCode = null;
                string afdRefInfo = null;
                try
                {
                    if (attempt == 1)
                    {
                        retryInfo?.InitialAttempt(request);
                    }

                    response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

                    if (attempt > 1)
                    {
                        TraceHttpRequestSucceededWithRetry(traceActivity, response, attempt);
                    }

                    // Verify the response is successful or the status code is one that may be retried. 
                    if (response.IsSuccessStatusCode)
                    {
                        break;
                    }
                    else
                    {
                        statusCode = response.StatusCode;
                        afdRefInfo = response.Headers.TryGetValues(HttpHeaders.AfdResponseRef, out var headers) ? headers.First() : null;
                        canRetry = m_retryOptions.IsRetryableResponse(response);
                    }
                }
                catch (HttpRequestException ex)
                {
                    exception = ex;
                    canRetry = VssNetworkHelper.IsTransientNetworkException(exception, m_retryOptions, out statusCode, out webExceptionStatus, out socketError, out winHttpErrorCode, out curlErrorCode);
                }
                catch (TimeoutException)
                {
                    throw;
                }

                if (attempt < maxAttempts && canRetry)
                {
                    backoff = BackoffTimerHelper.GetExponentialBackoff(attempt, minBackoff, m_retryOptions.MaxBackoff, m_retryOptions.BackoffCoefficient);
                    retryInfo?.Retry(backoff);
                    TraceHttpRequestRetrying(traceActivity, request, attempt, backoff, statusCode, webExceptionStatus, socketError, winHttpErrorCode, curlErrorCode, afdRefInfo);
                }
                else
                {
                    if (attempt < maxAttempts)
                    {
                        if (exception == null)
                        {
                            TraceHttpRequestFailed(traceActivity, request, statusCode != null ? statusCode.Value : (HttpStatusCode)0, afdRefInfo);
                        }
                        else
                        {
                            TraceHttpRequestFailed(traceActivity, request, exception);
                        }
                    }
                    else
                    {
                        TraceHttpRequestFailedMaxAttempts(traceActivity, request, attempt, statusCode, webExceptionStatus, socketError, winHttpErrorCode, curlErrorCode, afdRefInfo);
                    }
                    break;
                }

                // Make sure to dispose of this so we don't keep the connection open
                if (response != null)
                {
                    response.Dispose();
                }

                attempt++;
                TraceRaw(request, 100011, TraceLevel.Error,
                    "{{ \"Client\":\"{0}\", \"Endpoint\":\"{1}\", \"Attempt\":{2}, \"MaxAttempts\":{3}, \"Backoff\":{4} }}",
                    m_clientName,
                    request.RequestUri.Host,
                    attempt,
                    maxAttempts,
                    backoff.TotalMilliseconds);
                await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
            }

            if (exception != null)
            {
                throw exception;
            }

            return response;
        }

19 View Source File : HttpStreamParser.cs
License : MIT License
Project Creator : 1iveowl

private async Task<byte[]> ReadBytesAsync(Stream stream, CancellationToken ct)
        {
            if (_parserDelegate.RequestResponse.IsEndOfRequest || HasParsingError)
            {
                IsDone = true;
                return Enumerable.Empty<byte>().ToArray();
            }

            if (ct.IsCancellationRequested)
            {
                return Enumerable.Empty<byte>().ToArray();
            }

            var b = new byte[1];
            
            if (stream == null)
            {
                throw new Exception("Read stream cannot be null.");
            }

            if (!stream.CanRead)
            {
                throw new Exception("Stream connection have been closed.");
            }

            var bytesRead = 0;

            try
            {
                //Debug.WriteLine("Reading byte.");
                bytesRead = await stream.ReadAsync(b, 0, 1, ct).ConfigureAwait(false);
                //Debug.WriteLine("Done reading byte.");
            }
            catch (Exception ex)
            {
                HasParsingError = true;
                throw new SimpleHttpListenerException("Unable to read network stream.", ex);
            }

            if (bytesRead < b.Length)
            {
                IsDone = true;
            }

            return _errorCorrections.Contains(ErrorCorrection.HeaderCompletionError) 
                ? ResilientHeader(b) 
                : b;
        }

19 View Source File : IssuedTokenProvider.cs
License : MIT License
Project Creator : actions

public async Task<IssuedToken> GetTokenAsync(VssTraceActivity traceActivity)
            {
                IssuedToken token = null;
                try
                {
                    VssHttpEventSource.Log.IssuedTokenAcquiring(traceActivity, this.Provider);
                    if (this.Provider.InvokeRequired)
                    {
                        // Post to the UI thread using the scheduler. This may return a new task object which needs
                        // to be awaited, since once we get to the UI thread there may be nothing to do if someone else
                        // preempts us.

                        // The cancellation token source is used to handle race conditions between scheduling and 
                        // waiting for the UI task to begin execution. The callback is responsible for disposing of
                        // the token source, since the thought here is that the callback will run eventually as the
                        // typical reason for not starting execution within the timeout is due to a deadlock with
                        // the scheduler being used.
                        var timerTask = new TaskCompletionSource<Object>();
                        var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3));
                        timeoutTokenSource.Token.Register(() => timerTask.SetResult(null), false);

                        var uiTask = Task.Factory.StartNew((state) => PostCallback(state, timeoutTokenSource),
                                                            this,
                                                            this.CancellationToken,
                                                            TaskCreationOptions.None,
                                                            this.Provider.Credential.Scheduler).Unwrap();

                        var completedTask = await Task.WhenAny(timerTask.Task, uiTask).ConfigureAwait(false);
                        if (completedTask == uiTask)
                        {
                            token = uiTask.Result;
                        }
                    }
                    else
                    {
                        token = await this.Provider.OnGetTokenAsync(this.FailedToken, this.CancellationToken).ConfigureAwait(false);
                    }

                    CompletionSource.TrySetResult(token);
                    return token;
                }
                catch (Exception exception)
                {
                    // Mark our completion source as failed so other waiters will get notified in all cases
                    CompletionSource.TrySetException(exception);
                    throw;
                }
                finally
                {
                    this.Provider.CurrentToken = token ?? this.FailedToken;
                    VssHttpEventSource.Log.IssuedTokenAcquired(traceActivity, this.Provider, token);
                }
            }

19 View Source File : Program.cs
License : MIT License
Project Creator : acid-chicken

public static async Task Main(string[] args)
        {
            if (File.Exists(ConfigurePath))
            {
                ApplicationConfig = await LoadConfigAsync().ConfigureAwait(false);
            }
            else
            {
                await SaveConfigAsync(new Config()).ConfigureAwait(false);
                return;
            }

            DiscordClientConfig = new DiscordSocketConfig()
            {
                LogLevel = LogSeverity.Verbose
            };
            DiscordClient = new DiscordSocketClient(DiscordClientConfig);
            DiscordClient.Log += RequestLogAsync;
            DiscordClient.Ready += () => Task.WhenAny(/* NotificationManager.InitAsync() ,*/ TippingManager.WorkAsync(), /* MonitorManager.WorkAsync() ,*/ TickerManager.WorkAsync(), Task.Delay(0));

            await ModuleManager.InstallAsync().ConfigureAwait(false);

            await DiscordClient.LoginAsync(TokenType.Bot, ApplicationConfig.DiscordToken).ConfigureAwait(false);
            await DiscordClient.StartAsync().ConfigureAwait(false);

            while (!CancellationTokenSource.Token.IsCancellationRequested)
            {
                await Task.Delay(1024).ConfigureAwait(false);
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : acid-chicken

public static async Task<Config> LoadConfigAsync(string path = ConfigurePath)
        {
            Config result;
            try
            {
                using (var stream = File.OpenRead(path))
                using (var reader = new StreamReader(stream))
                {
                    result = JsonConvert.DeserializeObject<Config>(await reader.ReadToEndAsync().ConfigureAwait(false));
                    await RequestLogAsync(new LogMessage(LogSeverity.Verbose, "Program", "The config has been loaded successfully.")).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                await RequestLogAsync(new LogMessage(LogSeverity.Error, "Program", ex.Message, ex)).ConfigureAwait(false);
                throw;
            }
            return result;
        }

19 View Source File : B2CAuthService.cs
License : MIT License
Project Creator : 1iveowl

private async Task ExecuteSynchronously(Func<Task> task)
        {
            await _semapreplaced.WaitAsync().ConfigureAwait(false);

            try
            {
                await task();
            }
            finally
            {
                _semapreplaced.Release();
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : acid-chicken

public static async Task SaveConfigAsync(Config config, string path = ConfigurePath)
        {
            try
            {
                using (var stream = File.OpenWrite(path))
                using (var writer = new StreamWriter(stream))
                {
                    await writer.WriteLineAsync(JsonConvert.SerializeObject(config, Formatting.Indented)).ConfigureAwait(false);
                    await RequestLogAsync(new LogMessage(LogSeverity.Verbose, "Program", "The config has been saved successfully.")).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                await RequestLogAsync(new LogMessage(LogSeverity.Error, "Program", ex.Message, ex)).ConfigureAwait(false);
                throw;
            }
        }

19 View Source File : TaskHelpers.cs
License : MIT License
Project Creator : abdullin

public static async Task Then<T>(this Task<T> task, [NotNull] Action<T> inlineContinuation)
		{
			// Note: we use 'await' instead of ContinueWith, so that we can give the caller a nicer callstack in case of errors (instead of an AggregateExecption)

			var value = await task.ConfigureAwait(false);
			inlineContinuation(value);
		}

19 View Source File : AuthApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public virtual async Task<JwtTokenResponse> GetJwtTokenAsync(string username, string preplacedword)
        {
            return await GetJwtTokenAsync(new JwtTokenRequestBody
            {
                Username = username,
                Preplacedword = preplacedword
            }).ConfigureAwait(false);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : acid-chicken

public static async Task RequestLogAsync(LogMessage message)
        {
            await Task.WhenAny
            (
                LogAsync(message),
                Task.Delay(0)
            ).ConfigureAwait(false);
        }

19 View Source File : WaitForBackgroundThread.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter()
        {
            return Task.Run(() => { }).ConfigureAwait(false).GetAwaiter();
        }

19 View Source File : DocumentApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public virtual async Task<T> GetDoreplacedentAsync<T>(
            string collectionName, string doreplacedentKey, DoreplacedentHeaderProperties headers = null)
        {
            return await GetDoreplacedentAsync<T>(
                $"{WebUtility.UrlEncode(collectionName)}/{WebUtility.UrlEncode(doreplacedentKey)}", headers)
                .ConfigureAwait(false);
        }

19 View Source File : TcpClientEx.cs
License : MIT License
Project Creator : 1iveowl

private static async Task<byte[]> ReadOneByteAtTheTimeAsync(Stream stream, CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return Enumerable.Empty<byte>().ToArray();
            }

            var oneByteArray = new byte[1];

            try
            {
                if (stream == null)
                {
                    throw new Exception("Read stream cannot be null.");
                }

                if (!stream.CanRead)
                {
                    throw new Exception("Stream connection have been closed.");
                }

                var bytesRead = await stream.ReadAsync(oneByteArray, 0, 1, ct).ConfigureAwait(false);

                if (bytesRead < oneByteArray.Length)
                {
                    throw new Exception("Stream connection aborted unexpectedly. Check connection and socket security version/TLS version).");
                }
            }
            catch (ObjectDisposedException)
            {
                Debug.WriteLine("Ignoring Object Disposed Exception - This is an expected exception.");
                return Enumerable.Empty<byte>().ToArray();
            }
            catch (IOException)
            {
                return Enumerable.Empty<byte>().ToArray();
            }

            return oneByteArray;
        }

19 View Source File : DocumentApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public virtual async Task<DeleteDoreplacedentResponse<object>> DeleteDoreplacedentAsync(
            string doreplacedentId,
            DeleteDoreplacedentQuery query = null,
            DoreplacedentHeaderProperties headers = null)
        {
            return await DeleteDoreplacedentAsync<object>(doreplacedentId, query, headers).ConfigureAwait(false);
        }

19 View Source File : PageRepositoryBuilder.cs
License : Apache License 2.0
Project Creator : acblog

public override async Task Build(IList<Page> data)
        {
            await base.Build(data).ConfigureAwait(false);
            await BuildRouteIndex(data).ConfigureAwait(false);
        }

19 View Source File : DocumentApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public virtual async Task<DeleteDoreplacedentsResponse<object>> DeleteDoreplacedentsAsync(
            string collectionName,
            IList<string> selectors,
            DeleteDoreplacedentsQuery query = null,
            DoreplacedentHeaderProperties headers = null)
        {
            return await DeleteDoreplacedentsAsync<object>(collectionName, selectors, query, headers).ConfigureAwait(false);
        }

19 View Source File : TcpListenerEx.cs
License : MIT License
Project Creator : 1iveowl

private static async Task<TcpClient> WaitForNextRequestAsync(TcpListener tcpListener)
        {
            Debug.WriteLine("Ready for next Tcp Connection.");

            return await tcpListener.AcceptTcpClientAsync().ConfigureAwait(false);
        }

19 View Source File : DocumentApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public virtual async Task<HeadDoreplacedentResponse> HeadDoreplacedentAsync(
            string collectionName,
            string doreplacedentKey,
            DoreplacedentHeaderProperties headers = null)
        {
            return await HeadDoreplacedentAsync(
                $"{WebUtility.UrlEncode(collectionName)}/{WebUtility.UrlEncode(doreplacedentKey)}",
                headers).ConfigureAwait(false);
        }

19 View Source File : RecordFSBuilderBase.cs
License : Apache License 2.0
Project Creator : acblog

protected virtual async Task BuildData(IList<T> data)
        {
            List<TId> ids = new List<TId>();

            foreach (var v in data)
            {
                var id = v.Id?.ToString() ?? throw new NullReferenceException(nameof(v.Id));
                await using var st = FSStaticBuilder.GetFileRewriteStream(Paths.GetDataFile(RootPath, id));
                await JsonSerializer.SerializeAsync(st, v).ConfigureAwait(false);
                ids.Add(v.Id);
            }

            await BuildDataIdList(ids, Paths.GetConfigRoot(RootPath)).ConfigureAwait(false);
        }

19 View Source File : TaskCancellationExtensions.cs
License : MIT License
Project Creator : actions

public static async Task<TResult> EnforceCancellation<TResult>(
            this Task<TResult> task,
            CancellationToken cancellationToken,
            Func<string> makeMessage = null,
            [CallerFilePath] string file = "",
            [CallerMemberName] string member = "",
            [CallerLineNumber] int line = -1)
        {
            ArgumentUtility.CheckForNull(task, nameof(task));

            // IsCompleted will return true when the task is in one of the three final states: RanToCompletion, Faulted, or Canceled.
            if (task.IsCompleted)
            {
                return await task;
            }

            var cancellationTcs = new TaskCompletionSource<bool>(RUN_CONTINUATIONS_ASYNCHRONOUSLY);
            using (cancellationToken.Register(() => cancellationTcs.SetResult(false)))
            {
                var completedTask = await Task.WhenAny(task, cancellationTcs.Task).ConfigureAwait(false);
                if (completedTask == task)
                {
                    return await task;
                }
            }

            // Even if our actual task actually did honor the cancellation token, there's still a race that our WaitForCancellation
            // task may have handled the cancellation more quickly.
            if (!cancellationToken.IsCancellationRequested)
            {
                throw new InvalidOperationException("Task ended but cancellation token is not marked for cancellation.");
            }

            // However, we'd ideally like to throw the cancellation exception from the original task if we can.
            // Thus, we'll give that task a few seconds to coallesce (e.g. write to a log) before we give up on it.
            int seconds = 3;
            var lastChanceTcs = new TaskCompletionSource<bool>(RUN_CONTINUATIONS_ASYNCHRONOUSLY);
            using (var lastChanceTimer = new CancellationTokenSource(TimeSpan.FromSeconds(seconds)))
            using (lastChanceTimer.Token.Register(() => lastChanceTcs.SetResult(false)))
            {
                var completedTask = await Task.WhenAny(task, lastChanceTcs.Task).ConfigureAwait(false);
                if (completedTask == task)
                {
                    return await task;
                }
            }

            // At this point, we've given up on waiting for this task.
            ObserveExceptionIfNeeded(task);

            string errorString = $"Task in function {member} at {file}:{line} was still active {seconds} seconds after operation was cancelled.";
            if (makeMessage != null)
            {
                errorString += $" {makeMessage()}";
            }

            throw new OperationCanceledException(errorString, cancellationToken);
        }

19 View Source File : DiscordRPforVSPackage.cs
License : GNU Affero General Public License v3.0
Project Creator : 1thenikita

[System.Diagnostics.Codereplacedysis.SuppressMessage("Usage", "VSTHRD100:Avoid async void methods")]
        private async void SolutionBeforeClosing() => await this.UpdatePresenceAsync(null).ConfigureAwait(true);

19 View Source File : IssuedTokenProvider.cs
License : MIT License
Project Creator : actions

public async Task<IssuedToken> WaitForTokenAsync(
                VssTraceActivity traceActivity,
                CancellationToken cancellationToken)
            {
                IssuedToken token = null;
                try
                {

                    VssHttpEventSource.Log.IssuedTokenWaitStart(traceActivity, this.Provider, this.ActivityId);
                token = await Task.Factory.ContinueWhenAll<IssuedToken>(new Task[] { CompletionSource.Task }, (x) => CompletionSource.Task.Result, cancellationToken).ConfigureAwait(false);
                }
                finally
                {
                    VssHttpEventSource.Log.IssuedTokenWaitStop(traceActivity, this.Provider, token);
                }

                return token;
            }

19 View Source File : RecordFSReaderBase.cs
License : Apache License 2.0
Project Creator : acblog

public override async IAsyncEnumerable<TId> All([EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            var result = await GetIdList(Paths.GetConfigRoot(RootPath), cancellationToken: cancellationToken)
                .ConfigureAwait(false);
            if (result is not null)
            {
                foreach (var item in result)
                    yield return item;
            }
        }

19 View Source File : FileContainerHttpClient.cs
License : MIT License
Project Creator : actions

[EditorBrowsable(EditorBrowsableState.Never)]
        public async Task<HttpResponseMessage> UploadFileAsync(
            Int64 containerId,
            String itemPath,
            Stream fileStream,
            byte[] contentId,
            Int64 fileLength,
            Boolean isGzipped,
            Guid scopeIdentifier,
            CancellationToken cancellationToken = default(CancellationToken),
            int chunkSize = c_defaultChunkSize,
            int chunkRetryTimes = c_defaultChunkRetryTimes,
            bool uploadFirstChunk = false,
            Object userState = null)
        {
            if (containerId < 1)
            {
                throw new ArgumentException(WebApiResources.ContainerIdMustBeGreaterThanZero(), "containerId");
            }

            if (chunkSize > c_maxChunkSize)
            {
                chunkSize = c_maxChunkSize;
            }

            // if a contentId is specified but the chunk size is not a 2mb multiple error
            if (contentId != null && (chunkSize % c_ContentChunkMultiple) != 0)
            {
                throw new ArgumentException(FileContainerResources.ChunksizeWrongWithContentId(c_ContentChunkMultiple), "chunkSize");
            }

            ArgumentUtility.CheckForNull(fileStream, "fileStream");

            ApiResourceVersion gzipSupportedVersion = new ApiResourceVersion(new Version(1, 0), 2);
            ApiResourceVersion requestVersion = await NegotiateRequestVersionAsync(FileContainerResourceIds.FileContainer, s_currentApiVersion, userState, cancellationToken).ConfigureAwait(false);

            if (isGzipped
                && (requestVersion.ApiVersion < gzipSupportedVersion.ApiVersion
                    || (requestVersion.ApiVersion == gzipSupportedVersion.ApiVersion && requestVersion.ResourceVersion < gzipSupportedVersion.ResourceVersion)))
            {
                throw new ArgumentException(FileContainerResources.GzipNotSupportedOnServer(), "isGzipped");
            }

            if (isGzipped && fileStream.Length >= fileLength)
            {
                throw new ArgumentException(FileContainerResources.BadCompression(), "fileLength");
            }

            HttpRequestMessage requestMessage = null;
            List<KeyValuePair<String, String>> query = AppendItemQueryString(itemPath, scopeIdentifier);

            if (fileStream.Length == 0)
            {
                // zero byte upload
                FileUploadTrace(itemPath, $"Upload zero byte file '{itemPath}'.");
                requestMessage = await CreateRequestMessageAsync(HttpMethod.Put, FileContainerResourceIds.FileContainer, routeValues: new { containerId = containerId }, version: s_currentApiVersion, queryParameters: query, userState: userState, cancellationToken: cancellationToken).ConfigureAwait(false);
                return await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
            }

            bool multiChunk = false;
            int totalChunks = 1;
            if (fileStream.Length > chunkSize)
            {
                totalChunks = (int)Math.Ceiling(fileStream.Length / (double)chunkSize);
                FileUploadTrace(itemPath, $"Begin chunking upload file '{itemPath}', chunk size '{chunkSize} Bytes', total chunks '{totalChunks}'.");
                multiChunk = true;
            }
            else
            {
                FileUploadTrace(itemPath, $"File '{itemPath}' will be uploaded in one chunk.");
                chunkSize = (int)fileStream.Length;
            }

            StreamParser streamParser = new StreamParser(fileStream, chunkSize);
            SubStream currentStream = streamParser.GetNextStream();
            HttpResponseMessage response = null;

            Byte[] dataToSend = new Byte[chunkSize];
            int currentChunk = 0;
            Stopwatch uploadTimer = new Stopwatch();
            while (currentStream.Length > 0 && !cancellationToken.IsCancellationRequested)
            {
                currentChunk++;

                for (int attempt = 1; attempt <= chunkRetryTimes && !cancellationToken.IsCancellationRequested; attempt++)
                {
                    if (attempt > 1)
                    {
                        TimeSpan backoff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));
                        FileUploadTrace(itemPath, $"Backoff {backoff.TotalSeconds} seconds before attempt '{attempt}' chunk '{currentChunk}' of file '{itemPath}'.");
                        await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
                        currentStream.Seek(0, SeekOrigin.Begin);
                    }

                    FileUploadTrace(itemPath, $"Attempt '{attempt}' for uploading chunk '{currentChunk}' of file '{itemPath}'.");

                    // inorder for the upload to be retryable, we need the content to be re-readable
                    // to ensure this we copy the chunk into a byte array and send that
                    // chunk size ensures we can convert the length to an int
                    int bytesToCopy = (int)currentStream.Length;
                    using (MemoryStream ms = new MemoryStream(dataToSend))
                    {
                        await currentStream.CopyToAsync(ms, bytesToCopy, cancellationToken).ConfigureAwait(false);
                    }

                    // set the content and the Content-Range header
                    HttpContent byteArrayContent = new ByteArrayContent(dataToSend, 0, bytesToCopy);
                    byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    byteArrayContent.Headers.ContentLength = currentStream.Length;
                    byteArrayContent.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(currentStream.StartingPostionOnOuterStream,
                                                                                                             currentStream.EndingPostionOnOuterStream,
                                                                                                             streamParser.Length);
                    FileUploadTrace(itemPath, $"Generate new HttpRequest for uploading file '{itemPath}', chunk '{currentChunk}' of '{totalChunks}'.");

                    try
                    {
                        if (requestMessage != null)
                        {
                            requestMessage.Dispose();
                            requestMessage = null;
                        }

                        requestMessage = await CreateRequestMessageAsync(
                            HttpMethod.Put,
                            FileContainerResourceIds.FileContainer,
                            routeValues: new { containerId = containerId },
                            version: s_currentApiVersion,
                            content: byteArrayContent,
                            queryParameters: query,
                            userState: userState,
                            cancellationToken: cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to create HttpRequest. Error: {ex.ToString()}.");
                        continue;
                    }

                    if (isGzipped)
                    {
                        //add gzip header info
                        byteArrayContent.Headers.ContentEncoding.Add("gzip");
                        byteArrayContent.Headers.Add("x-tfs-filelength", fileLength.ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }

                    if (contentId != null)
                    {
                        byteArrayContent.Headers.Add("x-vso-contentId", Convert.ToBase64String(contentId)); // Base64FormattingOptions.None is default when not supplied
                    }

                    FileUploadTrace(itemPath, $"Start uploading file '{itemPath}' to server, chunk '{currentChunk}'.");
                    uploadTimer.Restart();

                    try
                    {
                        if (response != null)
                        {
                            response.Dispose();
                            response = null;
                        }

                        response = await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to send request to server. Error: {ex.ToString()}.");
                        continue;
                    }

                    uploadTimer.Stop();
                    FileUploadTrace(itemPath, $"Finished upload chunk '{currentChunk}' of file '{itemPath}', elapsed {uploadTimer.ElapsedMilliseconds} (ms), response code '{response.StatusCode}'.");

                    if (multiChunk)
                    {
                        FileUploadProgress(itemPath, currentChunk, (int)Math.Ceiling(fileStream.Length / (double)chunkSize));
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        break;
                    }
                    else if (IsFastFailResponse(response))
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request and cannot continue.");
                        break;
                    }
                    else
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request.");
                        continue;
                    }
                }

                // if we don't have success then bail and return the failed response
                if (!response.IsSuccessStatusCode)
                {
                    break;
                }

                if (contentId != null && response.StatusCode == HttpStatusCode.Created)
                {
                    // no need to keep uploading since the server said it has all the content
                    FileUploadTrace(itemPath, $"Stop chunking upload the rest of the file '{itemPath}', since server already has all the content.");
                    break;
                }

                currentStream = streamParser.GetNextStream();
                if (uploadFirstChunk)
                {
                    break;
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            return response;
        }

19 View Source File : Compressor.cs
License : MIT License
Project Creator : 13xforever

public virtual async Task<long> CompressAsync(Stream source, Stream destination)
        {
            using (var memStream = new MemoryStream())
            {
                using (var compressed = CreateCompressionStream(memStream))
                    await source.CopyToAsync(compressed).ConfigureAwait(false);
                memStream.Seek(0, SeekOrigin.Begin);
                await memStream.CopyToAsync(destination).ConfigureAwait(false);
                return memStream.Length;
            }
        }

19 View Source File : IssuedTokenProvider.cs
License : MIT License
Project Creator : actions

public async Task<IssuedToken> GetTokenAsync(
            IssuedToken failedToken,
            CancellationToken cancellationToken)
        {
            IssuedToken currentToken = this.CurrentToken;
            VssTraceActivity traceActivity = VssTraceActivity.Current;
            Stopwatch aadAuthTokenTimer = Stopwatch.StartNew();
            try
            {
                VssHttpEventSource.Log.AuthenticationStart(traceActivity);

                if (currentToken != null)
                {
                    VssHttpEventSource.Log.IssuedTokenRetrievedFromCache(traceActivity, this, currentToken);
                    return currentToken;
                }
                else
                {
                    GetTokenOperation operation = null;
                    try
                    {
                        GetTokenOperation operationInProgress;
                        operation = CreateOperation(traceActivity, failedToken, cancellationToken, out operationInProgress);
                        if (operationInProgress == null)
                        {
                            return await operation.GetTokenAsync(traceActivity).ConfigureAwait(false);
                        }
                        else
                        {
                            return await operationInProgress.WaitForTokenAsync(traceActivity, cancellationToken).ConfigureAwait(false);
                        }
                    }
                    finally
                    {
                        lock (m_thisLock)
                        {
                            m_operations.Remove(operation);
                        }

                        operation?.Dispose();
                    }
                }
            }
            finally
            {
                VssHttpEventSource.Log.AuthenticationStop(traceActivity);

                aadAuthTokenTimer.Stop();
                TimeSpan getTokenTime = aadAuthTokenTimer.Elapsed;

                if(getTokenTime.TotalSeconds >= c_slowTokenAcquisitionTimeInSeconds)
                {
                    // It may seem strange to preplaced the string value of TotalSeconds into this method, but testing
                    // showed that ETW is persnickety when you register a method in an EventSource that doesn't
                    // use strings or integers as its parameters. It is easier to simply give the method a string
                    // than figure out to get ETW to reliably accept a double or TimeSpan.
                    VssHttpEventSource.Log.AuthorizationDelayed(getTokenTime.TotalSeconds.ToString());
                }
            }
        }

19 View Source File : TippingManager.cs
License : MIT License
Project Creator : acid-chicken

public static async Task<string> InvokeMethodAsync(params object[] args)
        {
            using (var process = Process.Start(new ProcessStartInfo("bitzeny-cli", string.Join(' ', args.Select(x => x == null || x is bool || x is sbyte || x is byte || x is short || x is ushort || x is int || x is uint || x is long || x is ulong || x is float || x is double || x is decimal ? x.ToString() : $"\"{x}\"")))
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }))
            using (var reader = process.StandardOutput)
            {
                var output = await reader.ReadToEndAsync().ConfigureAwait(false);
                process.WaitForExit();
                process.Close();
                return output.Trim();
            }
        }

19 View Source File : SmtpMail.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Send(MailModel message)
        {
            await Task.Run(() =>
            {
                try
                {
                    SmtpClient client = new SmtpClient(_appConfig.Email.SmtpServer, _appConfig.Email.SmtpPort);
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(_appConfig.Email.AccountName, _appConfig.Email.Preplacedword);
                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From = new MailAddress(_appConfig.Email.AccountName, _appConfig.Email.FromAlias);
                    mailMessage.To.Add(message.Address);
                    mailMessage.Body = message.Content;
                    mailMessage.Subject = message.Subject;
                    mailMessage.IsBodyHtml = true;
                    client.Send(mailMessage);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "SendEmail Exception");
                    throw ex;
                }

            }).ConfigureAwait(false);
        }

19 View Source File : Compressor.cs
License : MIT License
Project Creator : 13xforever

public virtual async Task<long> DecompressAsync(Stream source, Stream destination)
        {
            using (var memStream = new MemoryStream())
            {
                using (var decompressed = CreateDecompressionStream(source))
                    await decompressed.CopyToAsync(memStream).ConfigureAwait(false);
                memStream.Seek(0, SeekOrigin.Begin);
                await memStream.CopyToAsync(destination).ConfigureAwait(false);
                return memStream.Length;
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 13xforever

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

19 View Source File : B2CAuthService.cs
License : MIT License
Project Creator : 1iveowl

private async Task<T> ExecuteSynchronously<T>(Func<Task<T>> task)
        {
            await _semapreplaced.WaitAsync().ConfigureAwait(false);

            try
            {
                return await task();
            }
            finally
            {
                _semapreplaced.Release();
            }

        }

19 View Source File : TaskHelpers.cs
License : MIT License
Project Creator : abdullin

public static async Task<R> Then<T, R>(this Task<T> task, [NotNull] Func<T, R> inlineContinuation)
		{
			// Note: we use 'await' instead of ContinueWith, so that we can give the caller a nicer callstack in case of errors (instead of an AggregateExecption)

			var value = await task.ConfigureAwait(false);
			return inlineContinuation(value);
		}

19 View Source File : TippingManager.cs
License : MIT License
Project Creator : acid-chicken

public static async Task<HashSet<IUser>> GetUsersAsync(IChannel channel, IUser exclude, decimal credit = decimal.Zero) =>
            JsonConvert
                .DeserializeObject<Dictionary<string, decimal>>(await InvokeMethodAsync("listaccounts").ConfigureAwait(false))
                .Where
                (user =>
                    user.Key.StartsWith("discord:") &&
                    user.Value >= 10 &&
                    channel
                        .GetUsersAsync()
                        .Flatten()
                        .Result
                            .Where(x => x.Id != exclude.Id)
                            .Select(x => $"discord:{x.Id}")
                            .Contains(user.Key)
                )
                .Select(x => (IUser)DiscordClient.GetUser(ulong.TryParse(new string(x.Key.Skip(8).ToArray()), out ulong result) ? result : 0))
                .ToHashSet();

See More Examples