![](/img/trans.png)
[英]How do I make an async method return Task<IEnumerable<T>>?
[英]How to return a Task<T> in an async method
我在Windows Phone 8應用程序中有此方法,可以從URL中獲取一些數據
public async static Task<byte[]> getData(string url)
{
HttpClient client = null;
HttpResponseMessage response = null;
Stream stream = null;
byte[] dataBytes = null;
bool error = false;
try
{
Uri uri = new Uri(url);
client = new HttpClient();
response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
stream = await response.Content.ReadAsStreamAsync();
dataBytes = getDataBytes(stream);
if (dataBytes == null)
{
error = true;
}
else if (dataBytes.Length == 0)
{
error = true;
}
}
catch (HttpRequestException )
{
}
if (error)
{
return getData(url); // this is where the issue is
}
return dataBytes;
}
但是由於該方法是異步方法,所以返回類型不能是Task,就像我在行上所做的return getData(url);
因為getData(string)
返回Task。 關於如何重寫它以使其起作用的任何想法?
等待getData
的結果可能會成功。 盡管如此,我還是強烈建議您使用循環重寫您的方法,而不是遞歸地再次調用該方法。 它使其難以閱讀,並可能導致無法預料的問題。
public async static Task<byte[]> getData(string url)
{
bool success = false;
byte[] dataBytes = null;
while (!success)
{
try
{
Uri uri = new Uri(url);
var client = new HttpClient();
var response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
var stream = await response.Content.ReadAsStreamAsync();
dataBytes = getDataBytes(stream);
success = dataBytes != null && dataBytes.Length > 0;
}
catch (HttpRequestException)
{
}
}
return dataBytes;
}
您可以通過將return更改為以下內容來避免編譯錯誤:
if (error)
{
return await getData(url); // this is where the issue is
}
我希望您確實意識到只要沒有數據返回,該代碼就會繼續循環? 有許多這樣的客戶端很容易使服務器過載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.