我有这个功能:
public async static Task<JsonObject> GetObject(string api)
{
try
{
JsonObject jsonObject = new JsonObject();
if (!IsInternetConnected())
{
string x = await DataBase.readStringFromLocalFile(api + ".txt");
jsonObject = JsonObject.Parse(x);
}
else
{
string x = "";
XDocument doc = XDocument.Load("DataLibrary/apis.xml");
var items = doc.Descendants("string");
foreach (XElement item in items)
{
if (item.Attribute("name").Value == api)
{
HttpClient webclient = new HttpClient();
HttpResponseMessage resp = webclient.PostAsync(new Uri(item.Value.ToString()), null).Result; //here
x = await resp.Content.ReadAsStringAsync();
try
{
await DataBase.saveStringToLocalFile(api + ".txt", x);
Debug.WriteLine("after writing");
}
catch (Exception ex)
{
throw ex;
}
Debug.WriteLine("after after writing");
jsonObject = JsonObject.Parse(x);
break;
}
}
}
return jsonObject;
}
catch (Exception)
{
MainPage.ShowCustomMessage(request_error_allert);
return new JsonObject();
}
}
这是我从这篇文章中获取的 saveStringToFile 函数:https ://pumpkinszwan.wordpress.com/2014/10/27/read-and-write-text-files-windows-8-1-phone-8-1 -通用应用程序/
public static async Task saveStringToLocalFile(string filename, string content)
{
// saves the string 'content' to a file 'filename' in the app's local storage folder
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(content.ToCharArray());
Debug.WriteLine("1");
// create a file with the given filename in the local folder; replace any existing file with the same name
StorageFile newFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
Debug.WriteLine("2");
// write the char array created from the content string into the file
using (var stream = await newFile.OpenStreamForWriteAsync())
{
await stream.WriteAsync(fileBytes, 0, fileBytes.Length);
Debug.WriteLine("3");
}
Debug.WriteLine("4");
}
我使用 2 个不同的 API 调用 GetObject 2 次。当代码到达 saveStringToFile 函数时,它会崩溃:
有时它会在 Debug.WriteLine("1"); 之后在 saveStringTofile 内崩溃;
有时在 Debug.WriteLine("2"); 之后
有时在 Debug.WriteLine("3"); 之后
有时在 Debug.WriteLine("after writing");
有时它第一次使用第一个 API 并在第二个 API 中崩溃。
它的行为真的很奇怪,我试图用每个断点来捕捉它,但它每次都会随机崩溃。有什么我想念的吗?