【发布时间】:2019-10-01 11:41:12
【问题描述】:
谁能告诉我为什么我的代码每次都返回相同的字符串?
public MainPage()
{
this.InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(5);
timer.Tick += OnTimerTick;
timer.Start();
}
private void OnTimerTick(object sender, object e)
{
getData();
HubText.Text = dumpstr;
}
private async void getData()
{
// Create an HttpClient instance
HttpClient client = new HttpClient();
var uri = new Uri("http://192.168.4.160:8081/v");
try
{
// Send a request asynchronously continue when complete
HttpResponseMessage response = await client.GetAsync(uri);
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously
dumpstr = await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
//throw;
}
}
string dumpstr;
所以每 5 秒我都会收到与第一个请求中相同的字符串。 我做错了什么?
【问题讨论】:
-
您实际上并没有等到得到数据才显示它。您最好将
getData()方法设为异步Task<string>方法,然后您的计时器滴答处理程序也可以是异步的,主体为HubText.Text = await getData();。目前,我希望您看到下一个值晚了 5 秒。但是由于您没有告诉我们任何有关该 URL 的返回内容的信息,我们不知道它为什么会改变。 -
我发现了另一种方法:使用 System.Net.Http 对抗 Windows.Net.Http;
标签: c# wpf windows-store-apps