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 = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X";
      public static async Task GetCurrencyExchangeAsync(decimal exchange, string fromCurrency, string toCurrency, Action<decimal> action)
       {
           try
           {
               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;
                   }
               }
               action(converted);
           }
           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;
    }).ConfigureAwait(false);
 
    return View();
}

Unit test is here:

[TestMethod]
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) ;
    Assert.IsNotNull(result.TempData["ConvertedResult"]);
}

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

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

James,
.ConfigureAwait(false) basically means that you don't have to switch thread contexts back to the original thread context.
See this for more details
msdn.microsoft.com/en-us/magazine/gg598924.aspx

Add comment