简体   繁体   中英

How to return a Task<T> in an async method

I have this method in my Windows Phone 8 app where I get some data from a 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;
    }

But since the method is an async one, the return type cannot be a Task, like I have done on the line return getData(url); since getData(string) returns Task. Any ideas on how I can rewrite this to make it work?

Awaiting the result of getData may do the trick. Still, I strongly recommand you to rewrite your method with a loop, rather than recursively call the method again. It makes it hard to read, and may lead to unforeseen issues.

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;
}

you can get around the compile error by adding changing the return to the following :

if (error)
{
return await getData(url); // this is where the issue is
}

I hope you do realize that this code will keep on looping as long as no data is returned? having many clients like this could easily overload your server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM