2014-07-12 52 views
0

我試圖從async html helper返回值,但它給出以下字符串而不是所需的值。無法從視圖中的異步方法返回值

「System.Threading.Tasks.Task + WhenAllPromise`1 [System.Decimal]」

方法:

public async static Task<decimal> CalculateCurrency(this HtmlHelper helper, decimal amount, string from, string country) 
    { 
     if (await getValue(country)) 
     { 
      string fromCurrency = string.IsNullOrEmpty(from) ? "USD" : from; 
      string toCurrency = country; 
      WebClient client = new WebClient(); 
      string url = string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X", fromCurrency.ToUpperInvariant(), toCurrency.ToUpperInvariant()); 
      Stream response = await client.OpenReadTaskAsync(url); 
      StreamReader reader = new StreamReader(response); 
      string yahooResponse = await reader.ReadLineAsync(); 
      response.Close(); 
      if (!string.IsNullOrWhiteSpace(yahooResponse)) 
      { 
       string[] values = Regex.Split(yahooResponse, ","); 
       if (values.Length > 0) 
       { 
        decimal rate = System.Convert.ToDecimal(values[1]); 
        string res = string.Format("{0:0.00}", rate * amount); 
        return decimal.Parse(res); 
       } 
      } 
      return decimal.Zero; 
     } 
     return decimal.Zero; 
    } 

呼叫HTML輔助:

@Html.CalculateCurrency(22, "USD", "EUR") 
+0

從視圖中調用異步代碼不是一個好主意。 – DavidG

+0

@DavidG我該如何解決這個問題?我想要該方法運行異步 – Anony

+0

在方法內部執行異步工作但同步返回。 – DavidG

回答

4

視圖不支持異步方法。因此,你會得到結果類型的默認.ToString()函數的結果,它確實只返回類型名稱。

選項:

  • 移動代碼到控制器和異步頂層(非獨生子女)行動await打電話英寸通過數據模型,通過或ViewBag
  • 轉換爲真正的同步代碼,查看是否必須,如果無法把它從視圖或兒童行動
  • 嘗試.Result,但要注意死鎖。詳情請見await vs Task.Wait - Deadlock?

注意:將async代碼移動到子操作將無濟於事。