2013-10-07 48 views
0

我在我的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; 
    } 

得到一些數據,但返回任務 因爲該方法是一個異步一個,返回類型不能成爲一個任務,就像我在 return getData(url);行上所做的那樣,因爲 getData(string)返回任務。任何想法,我如何可以重寫這個,使其工作?

+0

什麼是'getData(url)'?你正在遞歸地調用相同的方法? –

+1

'返回await getData(url);'可以工作。但總的來說,你應該重寫你的方法來使用循環,而不是在發生錯誤時再次遞歸地調用它。 –

+0

@SriramSakthivel是的,我發生錯誤時遞歸地調用它。 –

回答

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

'error = dataBytes == null || dataBytes.Length == 0;'typo? –

+0

@SriramSakthivel我不確定,我在發佈後立即編輯了3或4次答案。這個版本應該是正確的。 –

+0

是的,現在是正確的 –

1

您可以通過添加改變返回以下繞過編譯錯誤:

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

我希望你要明白,這個代碼將繼續只要沒有數據返回的循環?有這樣的許多客戶端可能會輕鬆超載您的服務器。