Async / await
Before the C# 5.0, we had to write asynchronous methods with callbacks and be careful about error conditions. With "async" and "await" it's much more straight forward.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace AsyncHttpClient
{
/// <summary>
/// Tiny example of using HttpClient.GetAsync() with Generics.
/// Uses the REST API calls from the most excellent mysafeinfo.com for presidents and Beatles albums
/// This prints:
/// Requesting presidents
/// Requesting Beatles albums
/// ... waiting ...
/// first president = number: '1','', party: '', term: ''
/// first Beatles album = album name: 'Please Please Me (Mono)', date: '1963-03-22T00:00:00'
/// </summary>
public class President
{
public int president;
public string name, party, term;
public override string ToString() { return $"number: '{president}','{name}', party: '{party}', term: '{term}'"; }
}
public class BeatlesAlbum
{
public string album, date;
public override string ToString() { return $"album name: '{album}', date: '{date}'"; }
}
class AsyncHttpClientExample
{
private static void Main()
{
string presidentsUrl = "https://mysafeinfo.com/api/data?list=presidents&format=json";
string beatlesUrl = "https://mysafeinfo.com/api/data?list=beatlesalbums&format=json&select=ent,typ,rd&alias=ent=artist,typ=album,rd=date";
var asyncHttpClientExample = new AsyncHttpClientExample();
Console.Out.WriteLine("Requesting presidents");
var presidents = asyncHttpClientExample.GetAsync<List<President>>(presidentsUrl);
Console.Out.WriteLine("Requesting Beatles albums");
var albums = asyncHttpClientExample.GetAsync<List<BeatlesAlbum>>(beatlesUrl);
Console.Out.WriteLine("... waiting ...");
Console.Out.WriteLine("first president = {0}", presidents.Result[0]);
Console.Out.WriteLine("first Beatles album = {0}", albums.Result[0]);
}
private async Task<T> GetAsync<T>(string url)
{
HttpClient client = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
var jsonString = response.Content.ReadAsStringAsync().Result;
T result = JsonConvert.DeserializeObject<T>(jsonString);
return result;
}
}
}
Caller Information
Although the stack trace object can be used to get similar information, C# 5.0 let's us get calling information for logging much more cheaply as shown in this example.
using System;
using System.Runtime.CompilerServices;
namespace Practice
{
public class SeaSharp5
{
static void Main()
{
var seaSharp5 = new SeaSharp5();
seaSharp5.MyCoolMethod();
Console.Write("Press 'Enter' to exit.");Console.In.ReadLine();
}
public void MyCoolMethod()
{
//do some cool stuff here
LogMessage("logging stuff here.");
}
public void LogMessage(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Console.WriteLine("My Message: " + message);
Console.WriteLine("Calling method name: " + memberName);
Console.WriteLine("Source file path: " + sourceFilePath);
Console.WriteLine("Source line number of calling method: " + sourceLineNumber);
}
}
}
The output looks like this:
My Message: logging stuff here. Calling method name: MyCoolMethod Source file path: c:\Users\fincherm\Documents\Visual Studio 2015\Projects\Practice\Practice\SeaSharp5.cs Source line number of calling method: 17 Press 'Enter' to exit.