TPL Async Await in Console Apps I just picked up Async Await and I am trying to use Async Await in Console App along with TPL for querying webservices. The code works fine and I am able to get the speed using HttpClient and async. Wanted to know if I am overusing async/await and if there is anything that I should avoid and can be simplified further.

I have read Albahari's threading e-book and the following articles to understand the usage.

http://www.tugberkugurlu.com/archive/how-and-where-concurrent-asynchronous-io-with-asp-net-web-api

http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx

https://scalablenotions.wordpress.com/2015/05/02/tpl-and-async-await-best-practices-for-the-busy-developer/

class Program
{
    public class Member
    {
        public string N { get; set; }
        public string E { get; set; }
    }


    static void Main()
    {
        List&lt;Member&gt; list = new List&lt;Member&gt;();
        Task.Run(async () =&gt; { await SubscribeMembersusingAPI(list); }).GetAwaiter().GetResult();

    }

    // Define other methods and classes here
    public static async Task SubscribeMembersusingAPI(List&lt;Member&gt; members)
    {
        List&lt;string&gt; updateemailstosubscribed = new List&lt;string&gt;();
        HttpClient client = new HttpClient();

        try
        {
            await Task.WhenAll(members.Select(m =&gt; SubscribeusingAPI(client, m)));
        }
        catch (Exception e)
        {
            //logger.Error("Error in Async task", e);
        }
        return;
    }

    public static async Task&lt;bool&gt; SubscribeusingAPI(HttpClient client, Member member)
    {
        try
        {
            List&lt;KeyValuePair&lt;String, String&gt;&gt; listkvp = new List&lt;KeyValuePair&lt;string, string&gt;&gt;();
            listkvp.Add(new KeyValuePair&lt;string, string&gt;("e", member.E.Trim()));
            listkvp.Add(new KeyValuePair&lt;string, string&gt;("n", member.N.Trim()));
            listkvp.Add(new KeyValuePair&lt;string, string&gt;("boolean", "true"));
            FormUrlEncodedContent formpost = new FormUrlEncodedContent(listkvp);
            var response = await client.PostAsync("", formpost);
            string responsebody = await response.Content.ReadAsStringAsync();
            if (responsebody == "1" || responsebody == "Member present")
                return true;
            else
                Console.WriteLine(string.Format("FAIL, Error while subscribing e: {0}, n: {1}, response: {2}", member.E, member.N, responsebody));
        }
        catch (Exception e)
        {
            Console.WriteLine(string.Format("FAIL, Error while subscribing e: {0}, n: {1} ", member.E, member.N), e);
        }
        return false;
    }
}
Let’s try to apply SRP, and get rid of mutable state to increase code maintainability. It inflates C# code a little bit, but usually makes sense. 

Demo:

  IEnumerable&lt;Member&gt; members = new Member[] { new Member("n","e") };
  await members
      .SubscribeAsync()
      .LogAsync(Console.Out);


Where Member could be immutable:

public class Member
{
    public Member(string n, string e)
    {
        N = n.Trim();
        E = e.Trim();
    }

    public string N { get; }
    public string E { get; }
    public override string ToString() =&gt; $"N={N}, E={E}";
}


We will use this universal helper class to log task exceptions:

static class Logging
{
    public static async Task LogAsync(this Task task, TextWriter writer)
    {
        try
        {
            await task;
        }            
        catch (AggregateException ex)
        {
            foreach (var exx in ex.Flatten().InnerExceptions)
                await writer.WriteLineAsync(exx.Message);
        }
        catch(Exception ex)
        {
            await writer.WriteLineAsync(ex.Message);
        }
    }
}


Now subscription helpers:

static class Subscription
{
    public static Task SubscribeAsync(this IEnumerable&lt;Member&gt; members) =&gt;
        Task.WhenAll(from member in members
                     select member.SubscribeAsync());

    public static Task&lt;SubscriptionResponse&gt; SubscribeAsync(this Member member) =&gt;
        new SubscriptionRequest(member).ExecuteAsync();
}


Subscription request:

public class SubscriptionRequest
{
    const string RequestUrl = "";

    public SubscriptionRequest(Member member)
    {
        Member = member;
    }

    public async Task&lt;SubscriptionResponse&gt; ExecuteAsync()
    {
        using (var client = new HttpClient())
            try
            {
                var response = await client.PostAsync(RequestUrl, Content);
                var responseBody = await response.Content.ReadAsStringAsync();
                return new SubscriptionResponse(responseBody);
            }
            catch(Exception ex)
            {
                throw new SubscriptionException(Member, ex);
            }            
    }

    FormUrlEncodedContent Content =&gt; new FormUrlEncodedContent(Kvps);
    IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; Kvps =&gt; new[]
    {
        new KeyValuePair&lt;string, string&gt;("e", Member.E),
        new KeyValuePair&lt;string, string&gt;("n", Member.N),
        new KeyValuePair&lt;string, string&gt;("boolean", "true")
    };

    Member Member { get; } 
}


And response:

public class SubscriptionResponse
{
    public SubscriptionResponse(string body)
    {
        Body = body;
        if (!Success)
            throw new InvalidOperationException(body);
    }

    public bool Subscribed =&gt; Body == "1";
    public bool AlreadySubscribed =&gt; Body == "Member present";
    bool Success =&gt; Subscribed || AlreadySubscribed;
    string Body { get; }
}


The only missing part:

public class SubscriptionException : Exception
{
    public SubscriptionException(Member member, Exception error) :
        base($"{member} subscription failed, error: {error.Message}", error)
    {
    }
}


P.S. Generally speaking, C# is a pretty verbose language, so it is often punishing good programming practices…