Create a Currency Exchange Async in C#

Thanks to the new async and await keywords, asynchronous programming has gotten easier in .Net.

Today we will create an asynchronous currency conversion method using yahoo services (If you need to use this service commercially, you should contact yahoo).

public static readonly string ConversionServiceURL = "{0}{1}=X";
      public static async Task GetCurrencyExchangeAsync(decimal exchange, string fromCurrency, string toCurrency, Action<decimal> action)
               decimal converted = 0.0m;
               var client = new WebClient();
               string result = await client.DownloadStringTaskAsync(string.Format(ConversionServiceURL, toCurrency.ToUpper(), fromCurrency.ToUpper()));
               var split = result.Split(',');
               if (split != null && split.Length >= 0)
                   decimal rate;
                   if (Decimal.TryParse(split[1], out rate))
                       converted = rate * exchange;
           catch (WebException ex)
               //handle your exception here
               throw ex;

Here is how to use the method in an MVC application:

public async Task<ActionResult> Index(decimal total=100m, string fromCurrency="USD", string toCurrency="EUR")
    await Helper.GetCurrencyExchangeAsync(total, fromCurrency, toCurrency ,ConvertedValue =>
        TempData["ConvertedResult"] = ConvertedValue;
    return View();

Unit test is here:

public async Task Index_Should_Return_View_With_Converted_Currency()
    decimal testToConvert = 110.00m;
    string from = "USD";
    string to = "EUR";
    HomeController controller = new HomeController();
    var  result = (ViewResult)  await controller.Index(testToConvert, from, to) ;

One thing to remember, don't abuse async and await as they don't come without a performance cost.

More on asynchronous programming in .Net 4.5

Comments (2) -

James R Sven 3/21/2014 10:15:53 AM

What's the does the .ConfigureAwait(false) on line 8 do in your action?

.ConfigureAwait(false) basically means that you don't have to switch thread contexts back to the original thread context.
See this for more details

Comments are closed