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