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")
从视图中调用异步代码不是一个好主意。 – DavidG
@DavidG我该如何解决这个问题?我想要该方法运行异步 – Anony
在方法内部执行异步工作但同步返回。 – DavidG