簡體   English   中英

System.Threading.Tasks.Task`1 [ <myType> ]被退回

[英]System.Threading.Tasks.Task`1[<myType>] being returned

這似乎是為什么異步函數返回System.Threading.Tasks.Task`1 [System.String]的副本 但是我在做《答案》中建議的事情,但無濟於事。

我正在運行控制台應用程序:

    static void Main(string[] args)
    {
        ...

        var details = CallRestMethodAsync(url, filterObj);
        Console.Write(details);
        Console.ReadKey();

    }

    public static async Task<NotificationEvents> CallRestMethodAsync(string url, FilterPager filterPager = null)
    {
         ...
         var result = await response.Content.ReadAsStringAsync();
         return JsonConvert.DeserializeObject<NotificationEvents>(result, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
    }

當我在CallRestMethodAsync的最后一行放置一個斷點並檢查result ,我發現它確實包含預期的對象。 而且,JsonConvert不會引發錯誤。

但是我得到的輸出是:

System.Threading.Tasks.Task`1[NotificationsHandler.NotificationEvents]

更新(4/30/2019,11:09 CT):在接受@Martin Brown的回答后,我意識到我(愚蠢地)期望在控制台上看到我的類型輸出的字符串化實例。 當然那是行不通的。 我需要在Main內部做的是: var details = (CallRestMethodAsync(url, filterObj)).Result; // to force the Task to resolve to my type foreach (var result in details.Results) // Results being a (array) property Console.Write(details.Results[0].EventDate); // EventDate being a prop that the Console could actually output var details = (CallRestMethodAsync(url, filterObj)).Result; // to force the Task to resolve to my type foreach (var result in details.Results) // Results being a (array) property Console.Write(details.Results[0].EventDate); // EventDate being a prop that the Console could actually output

您的CallRestMethodAsync方法返回Task<NotificationEvents>而不是預期的NotificationEvents 您可以將Main方法設置為await CallRestMethodAsync的結果,如下所示:

static async Task Main(string[] args)
{
    ...

    var details = await CallRestMethodAsync(url, filterObj);
    Console.Write(details);
    Console.ReadKey();

}

如果使用的是.net的舊版本,則可能無法創建異步main方法。 在這種情況下,您將需要獲得以下任務的Result

static void Main(string[] args)
{
    ...

    var details = CallRestMethodAsync(url, filterObj);
    Console.Write(details.Result);
    Console.ReadKey();

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM