我是新手等待异步,我想了解我在这个真实场景中研究过的主题:
我有一个简单的代码,读取比特币价格需要1-2秒,我不想使用等待异步锁定UI,并仍然提供状态,如果它正在加载或完成:
private void button_Click(object sender, RoutedEventArgs e)
{
Task<int> bitcoinPriceTask = GetBitcoinPrice();
lblStatus.Content = "Loading...";
}
protected async Task<int> GetBitcoinPrice()
{
IPriceRetrieve bitcoin = new BitcoinPrice();
string price = bitcoin.GetStringPrice();
txtResult.Text = price;
lblStatus.Content = "Done";
return 1;
}
Run Code Online (Sandbox Code Playgroud)
根据要求,这里是BitcoinPrice类的实现:
public class BitcoinPrice : IPriceRetrieve
{
public BitcoinPrice()
{
Url = "https://www.google.com/search?q=bitcoin%20price";
}
public string Url { get; }
public string GetStringPrice()
{
var html = RetrieveContent();
html = MetadataUtil.GetFromTags(html, "1 Bitcoin = ", " US dollars");
return html;
}
public float GetPrice()
{
throw new NotImplementedException();
}
public string RetrieveContent()
{
var request = WebRequest.Create(Url);
var response = request.GetResponse();
var dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
var responseFromServer = reader.ReadToEnd();
return responseFromServer;
}
}
Run Code Online (Sandbox Code Playgroud)
你的代码现在有很多问题,首先你需要你的事件处理程序,async以便你可以等待返回的方法Task<int>,其次你可以在调用方法之前设置消息加载并等待它以便它等待该方法完成它,当它完成工作返回结果然后将消息设置为完成:
private async void button_Click(object sender, RoutedEventArgs e)
{
lblStatus.Content = "Loading...";
int bitcoinPriceTask = await GetBitcoinPrice();
lblStatus.Content = "Done";
}
protected async Task<int> GetBitcoinPrice()
{
IPriceRetrieve bitcoin = new BitcoinPrice();
string price = await bitcoin.GetStringPrice();
txtResult.Text = price;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
或者更好的可以返回Task<string>并在事件处理程序中设置TextBox值:
protected async Task<string> GetBitcoinPrice()
{
IPriceRetrieve bitcoin = new BitcoinPrice();
string price = await bitcoin.GetStringPrice();
return price;
}
Run Code Online (Sandbox Code Playgroud)
并在事件处理程序中:
private async void button_Click(object sender, RoutedEventArgs e)
{
lblStatus.Content = "Loading...";
string price = await GetBitcoinPrice();
txtResult.Text = price;
lblStatus.Content = "Done";
}
Run Code Online (Sandbox Code Playgroud)