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
class Program
{
public class Member
{
public string N { get; set; }
public string E { get; set; }
}
static void Main()
{
List<Member> list = new List<Member>();
Task.Run(async () => { await SubscribeMembersusingAPI(list); }).GetAwaiter().GetResult();
}
// Define other methods and classes here
public static async Task SubscribeMembersusingAPI(List<Member> members)
{
List<string> updateemailstosubscribed = new List<string>();
HttpClient client = new HttpClient();
try
{
await Task.WhenAll(members.Select(m => SubscribeusingAPI(client, m)));
}
catch (Exception e)
{
//logger.Error("Error in Async task", e);
}
return;
}
public static async Task<bool> SubscribeusingAPI(HttpClient client, Member member)
{
try
{
List<KeyValuePair<String, String>> listkvp = new List<KeyValuePair<string, string>>();
listkvp.Add(new KeyValuePair<string, string>("e", member.E.Trim()));
listkvp.Add(new KeyValuePair<string, string>("n", member.N.Trim()));
listkvp.Add(new KeyValuePair<string, string>("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;
}
}