如何在异步方法中返回Task <t> </t>

时间:2013-10-07 09:49:30

标签: c# windows-phone-8 task async-await

我在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。关于我如何重写它以使其有效的任何想法?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您可以通过添加将返回更改为以下内容来解决编译错误:

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

我希望您确实知道只要没有返回数据,此代码将继续循环?拥有这样的客户很容易使服务器过载。