2013-05-20 52 views
0

我試圖使用C#Facebook SDK檢索相冊的ID。但是我收到以下錯誤:訪問任務的結果屬性

System.Threading.Tasks.Task' does not contain a definition for 'Result' and no extension method 'Result' accepting a first argument of type 'System.Threading.Tasks.Task' could be found

請看下面的代碼,就在foreach線

try 
{ 
    string wallAlbumID = string.Empty; 
    FacebookClient client = new FacebookClient(accessToken); 
    client.GetTaskAsync(pageID + "/albums") 
     .ContinueWith(task => 
      { 
       if (!task.IsFaulted) 
       { 
        foreach (dynamic album in task.Result.data) 
        { 
         if (album["type"] == "wall") 
         { 
          wallAlbumID = album["id"].ToString(); 
         } 
        } 
       } 
       else 
       { 
        throw new DataRetrievalException("Failed to retrieve wall album ID.", task.Exception.InnerException); 
       } 
      }); 
    return wallAlbumID; 
} 

爲了記錄發生錯誤,則FacebookClient.GetTaskAsync方法返回Task<object>

+0

如果你調試代碼,並期待在運行時類型的「任務」,你會發現它是任務型的衍生物,你可能只是需要做一個演員,如'((SomeFacebookTaskType)任務).Result' – joshuahealy

回答

1

當我編譯你的代碼,我得到兩個錯誤,第一個是你提到的,第二個是:

'object' does not contain a definition for 'data' and no extension method 'data' accepting a first argument of type 'object' could be found

這第二個錯誤是你實際的錯誤:task.Resultobject,但是(我認爲)你想把它當作dynamic。由於這個錯誤,編譯器也嘗試使用ContinueWith()的過載,該過載僅使用Task,而不是Task<object>,這就是爲什麼你是也是得到第一個錯誤。

要修正這個錯誤,你應該投給task.Resultdynamic

dynamic result = task.Result; 
foreach (dynamic album in result.data) 

這將編譯很好,但它實際上並不會起作用,因爲你設置的局部變量,你從封閉方法返回後。

如果您正在使用C#5.0,你應該在這裏使用await,而不是ContinueWith()

try 
{ 
    dynamic result = await client.GetTaskAsync(pageID + "/albums"); 
    foreach (dynamic album in result.data) 
    { 
     if (album["type"] == "wall") 
     { 
      return (string)album["id"].ToString(); 
     } 
    } 
    return string.Empty; 
} 
catch (Exception e) // you should use a specific exception here, but I'm not sure which 
{ 
    throw new DataRetrievalException("Failed to retrieve wall album ID.", e); 
} 

如果您不能使用C#5.0,那麼你的整個方法應該返回多數民衆贊成由ContinueWith()返回Task<string>

return client.GetTaskAsync(pageID + "/albums") 
     .ContinueWith(
      task => 
      { 
       if (!task.IsFaulted) 
       { 
        dynamic result = task.Result; 
        foreach (dynamic album in result.data) 
        { 
         if (album["type"] == "wall") 
         { 
          return (string)album["id"].ToString(); 
         } 
        } 
        return string.Empty; 
       } 
       else 
       { 
        throw new DataRetrievalException(
         "Failed to retrieve wall album ID.", task.Exception.InnerException); 
       } 
      }); 
0

我不不知道Facebook的API,但錯誤似乎表明,你正在處理Task class (non-generic) which does not have Result property。它是the generic Task<T> derived from non-generic Task class that has the property。它們都允許異步運行代碼,但泛型類能夠運行返回值的方法。

如果GetTaskAsync返回Task而不是Task<T>,則表示您無法從中獲取結果,因爲它在後臺運行的操作不會返回任何內容。

+0

實際上,錯誤消息提示了這一點,但它實際上並不正確。 – svick