需要幫助..這是我的第一個應用程序。我想用JSON數據填充GridView。代碼如下工作,但現在我試圖將async private void haePostimerkitPilvesta()
和public static string ReadStreamAsString(Stream input)
方法代碼塊從MainPage.xaml.cs
移動到其他.cs文件,但沒有運氣。我應該如何編寫代碼以便我可以正確調用它?沒有異步方法我可以做同樣的事情,但代碼不起作用。如何從其他類文件調用異步方法
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
haePostimerkitPilvesta();
}
async private void haePostimerkitPilvesta()
{
Uri address = new Uri("xxx.json"); //public link of our file
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
WebResponse response = await request.GetResponseAsync();
Stream stream = response.GetResponseStream();
string content = ReadStreamAsString(stream);
GridViewPostimerkit.ItemsSource = JsonConvert.DeserializeObject(content, typeof(List<Postimerkit>));
}
public static string ReadStreamAsString(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return Encoding.UTF8.GetString(ms.ToArray(), 0, ms.ToArray().Count());
}
}
[同步調用異步方法]的可能的複製(http://stackoverflow.com/questions/22628087/calling-async-method-synchronously) – BlueTrin
嘗試http://stackoverflow.com/questions/22628087/同步調用異步方法 – BlueTrin
您是否在將私有方法更改爲公開時將其更改爲公共方法? –