logo
down
shadow

How to use HttpClient without async


How to use HttpClient without async

By : Barsha Sahoo
Date : November 21 2020, 11:01 PM
I think the issue was by ths following , Hello I'm following to this guide , Of course you can:
code :
public static string Method(string path)
{
   using (var client = new HttpClient())
   {
       var response = client.GetAsync(path).GetAwaiter().GetResult();
       if (response.IsSuccessStatusCode)
       {
            var responseContent = response.Content;
            return responseContent.ReadAsStringAsync().GetAwaiter().GetResult();
        }
    }
 }
using (var client = new WebClient())
{
    string response = client.DownloadString(path);
    if (!string.IsNullOrEmpty(response))
    {
       ...
    }
}


Share : facebook icon twitter icon
Task(async, await): Do I need to enter these are all connecting layers or only ones with ASYNC calls i.e HttpClient.GetA

Task(async, await): Do I need to enter these are all connecting layers or only ones with ASYNC calls i.e HttpClient.GetA


By : Graham
Date : March 29 2020, 07:55 AM
Hope that helps
I automatically added "async" on the controller, of course this now requires that I use await.
Async with HTTPClient

Async with HTTPClient


By : Golden Chrysanthem
Date : March 29 2020, 07:55 AM
Any of those help Calling Task.Result or Task.Wait on the UI thread can cause a deadlock that I explain in full on my blog.
To fix it, replace every use of Result or Wait with await
code :
public async Task<bool> IsAuthenticatedAsync(string _userName, string _password)
{
    return (bool) (_isAuthenticated ?? (_isAuthenticated = await AuthenticateAsync(_userName, _password)));
}

private async void BtnLogin_OnClick(object sender, RoutedEventArgs e)
{
    var user = new User();

    if (await user.IsAuthenticatedAsync(tbUserName.Text, tbPassword.Text))
    {
        NavigationService.Navigate(new Uri("/MainPage.xaml"));
    }
}
C#: Different results when using sync, async or async with shared HttpClient

C#: Different results when using sync, async or async with shared HttpClient


By : lantaozi
Date : March 29 2020, 07:55 AM
I hope this helps . @Igor has informed me about the deadlock issue in my second example.
So I currently used the HttpClient as such (async):
code :
private static async Task<string> GetAPI(string url)
    {
    // TODO: Use a shared instance of HttpClient
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("x-api-key", "SomeSecretApiKey");

        var jsonString = await client.GetStringAsync(url).ConfigureAwait(false);
        return jsonString;
    }
}
Async code appears to be partially blocking when calling multiple async tasks in a row (using HttpClient)

Async code appears to be partially blocking when calling multiple async tasks in a row (using HttpClient)


By : Greta W. Stevenson
Date : March 29 2020, 07:55 AM
like below fixes the issue When you do an await, the subsequent code gets executed only after what you 'awaited' gets completed.
To send multiple queries concurrently, you have to create new Task for each query and then await all of them together.
Yet Another HttpClient / Async Deadlock

Yet Another HttpClient / Async Deadlock


By : Arpit Saxena
Date : March 29 2020, 07:55 AM
Hope that helps So, with the help of @JSteward in the comments, he pointed out that async and Parrallel.ForEach aren't well suited to working together, since return types of void when dealing with async should be avoided.
He recommended that I use Async only, from the top (Button Click) to the bottom (Message Send), and that worked out. Credit to him for the guidance.
code :
private async Task<bool> SendFiles()
{
    var result = _InfoCollection.Select(SendFile);
    await Task.WhenAll(result).ConfigureAwait(false);
    return true;
}
Related Posts Related Posts :
  • Unable to resize StackPanel when IDataErrorInfo is triggered
  • How to stop "Update Background Files"?
  • Proper way to use dependency injection when some arguments will be known only at runtime
  • How to remove duplicate List in my List<List<int>> object?
  • Unable to cast object of type 'MongoDB.Bson.Serialization.Serializers.DateTimeSerializer' to type 'MongoDB.Bson.Serializ
  • Lightswitch submit a form on enter key
  • Business Logic in the JavaScript
  • tcp socket asynchronous communication
  • Syntax match using regex in c#
  • Display timerpickerdialog within a fragment using Xamarin Android
  • Get date of last seven days
  • Is there any reason to use very simple properties over fields?
  • C# Deserialize JSON to Object
  • dot instead of slash in c# file path
  • c# How to format mifare1k card
  • populate a combobox using another combobox selected item, in WPF
  • I need to check whether the data entered in form exists in database or not and if it exists redirect it to another page
  • Adding a Button in Summary Row - RadGrid Telerik Winforms
  • Timer not starting
  • Selecting elements inside UWP-Hub
  • How to setup Azure Notification Hub in C# backend
  • CollectionDataContract with the extra property
  • Modifying the resultant Executing assembly path c#
  • AutoGenrate the code
  • how to assign backspace as back key
  • Show message and Reload page in C# asp.net webform
  • How to allow only first punctuation mark in string with different marks sequence between words
  • Restore maximzed state on secondary monitor
  • MVC.Net Open a file in a new window instead of downloading
  • C# How to delete every character after something on every line
  • Entity Framework 6 stored procedure call resultset decimal value is 0
  • Accessing Non Static Method from another page
  • Random number generator, pick 3 in a range, returns group of 2 in some iterations
  • EPPlus number format
  • mvc razor does not redirect to url after action
  • Using SUM(Total). SQL statement works fine in PHP+MySQL
  • Regex - How to capture an arbitrary string appearing anywhere in a known string?
  • Passing parameters to stored procedure using EF6
  • How to find string with punctuation at the end
  • Bind a linkedlist to a datagridview
  • Entity Framework: determine sides of foreign key relation
  • C# Join Clause with association table
  • Rectangle contains Point returns false
  • OnEnable function from of ScriptableObject not being called
  • Encoding / Decoding 14-bit from Int to Hex and vice versa
  • Why getting error Cannot deserialize the current JSON object?
  • C# I can't print variable text in other Form
  • Issue on Getting Date Name of Day, Month, Date and Year
  • Entity Framework : update user fails
  • Calling a function from other script in Unity
  • How to add Roles to Windows Authentication in ASP.NET Core
  • Error installing Xamarin.Auth from NuGet
  • create relation between two tables
  • Discord.NET await outside command
  • Does the storage of PCM data of Mp3 File depends on Big Endian and little Endian?
  • XML data filtering and searching
  • Highlight selected tab in Xamarin Forms UWP
  • I have made a notifyicon in my application but i want to make it stay in system tray when application closes
  • What is the C# regex format to match +- signs or space?
  • Access controller data from ViewModel
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com