ear*_*ing 5 c# async-await windows-phone-8
我在两个WP8应用程序中使用了相同的方法.给定相同的url和相同的设备,该方法适用于一个应用程序,但不适用于另一个应用程序.在失败的应用程序中,GetAsync在调用后挂起.没有时间,没有例外.
这是有问题的方法.
private async Task<Byte[]> DownloadData(string uri)
{
byte[] myDataBuffer = null;
var newUri = new Uri(uri, UriKind.Absolute);
var myWebClient = new HttpClient();
var response = await myWebClient.GetAsync(newUri);
if (response.Content.Headers.ContentType.MediaType == "text/plain"
|| response.Content.Headers.ContentLength < 200)
{
throw new Exception(await response.Content.ReadAsStringAsync());
}
myDataBuffer = await response.Content.ReadAsByteArrayAsync();
return myDataBuffer;
}
Run Code Online (Sandbox Code Playgroud)
这种情况每次都发生在一个特定的应用程序上,而不是另一个.相同的设备.有没有人经历过这种行为?网址有效,代码相同.是否有可能影响此项目的项目设置?我在失败的应用程序的另一部分使用HttpClient,它在那里工作.
我可以更改代码以使用HttpWebRequest,并且工作正常.只是没有HttpClient.
我刚刚发现,如果我将方法复制到我的button_click处理程序中,它也可以在那里工作.在单独的类中有这个方法有问题吗?这对我来说似乎很奇怪.
更新
似乎打破它的是多层异步方法调用它.我在课堂上
public override byte[] GetImageData(string imageUri)
{
return GetImageDataAsync(imageUri).Result;
}
public async Task<byte[]> GetImageDataAsync(string imageUri)
{
return await DownloadData(imageUri);
}
Run Code Online (Sandbox Code Playgroud)
从我的button_click处理程序,我正在打电话GetImageData(uri).如果我改变await GetImageDataAsync(uri)它是有效的.
是Result不是要引用的正确属性GetImageData?
这是一个测试网址" http://www.rei.com/pix/common/REI_logo.gif "
Ste*_*ary 11
ResultWait正如我在博客中解释的那样,调用或可能导致死锁.
解决这个问题的正确方法是使用await.我假设你有一些理由要同步阻止,但最好使用await并找到一种方法使其在你的代码中运行.
| 归档时间: |
|
| 查看次数: |
8585 次 |
| 最近记录: |