簡體   English   中英

使用異步任務方法調用另一個任務方法-可能僅使用一個任務?

[英]Using an async Task method that calls another Task method - possible to use only one task?

我寫了一個通用的異步方法來從Web API獲取json

private static async Task<T> WebReq<T>(string url, string method)
    {
        // Init a HttpWebRequest for the call
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = method;

        using (var memoryStream = new MemoryStream())
        {
            // Send request to the internet and wait for the response
            using (var response = await httpWebRequest.GetResponseAsync())
            {
                // Get the datastream
                using (var responseStream = response.GetResponseStream())
                {
                    // Read bytes in the responseStream and copy them to the memoryStream 
                    await responseStream.CopyToAsync(memoryStream);
                }
            }

            // Read from the memoryStream
            using (var streamReader = new StreamReader(memoryStream))
            {
                var result = await streamReader.ReadToEndAsync();
                return JsonConvert.DeserializeObject<T>(result);
            }
        }             
    }

然后,我的所有方法都將使用該通用方法來調用API,例如

public static async Task<Dictionary<string, string>> GetExampleDictAsync(string id)
    {
        string url = baseUrl + "GetExampleDictionary/" + id;
        return await WebReq<Dictionary<string, string>>(url, "POST");
    }

據我了解,這將創建2個任務。 如果我每次都寫出WebReq的內容,那么每個調用將只有1個任務...如何使用我的通用方法並且僅啟動一個Task?

它就像不等待就返回WebReq一樣簡單嗎?

在我看來,這很好,我可能不會更改。 如果您擔心,可以將第二種方法的簽名更改為:

public static Task<Dictionary<string, string>> GetExampleDictAsync(string id)
{
    string url = baseUrl + "GetExampleDictionary/" + id;
    return WebReq<Dictionary<string, string>>(url, "POST");
}

然后,您只返回由內部方法創建的Task,可以在調用方中等待它-無需在此方法中等待它,因此它不需要異步。

但是,如果此方法在調用WebReq 之后需要執行任何WebReq ,那么它將受益於異步,因此我會在更改它之前進行考慮。

暫無
暫無

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

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