【发布时间】:2014-09-02 17:35:13
【问题描述】:
我正在尝试从async html 帮助器返回值,但它给出的是以下字符串而不是所需的值。
“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")
【问题讨论】:
-
从视图调用异步代码不是一个好主意。
-
@DavidG 我该如何解决这个问题?我希望该方法异步运行
-
在方法内部做异步工作,但同步返回。
-
@DavidG 我想提高应用程序性能,这就是我使用异步方法的原因,有没有其他方法可以做到这一点?或者我怎么能用这种方法做到这一点?
-
@Usama 很抱歉,我不会为您编写代码。我给了你一个正确的方向——开始研究吧!如果您遇到任何问题,请随时发布另一个问题!
标签: c# asp.net asp.net-mvc asp.net-mvc-4 async-await