簡體   English   中英

在異步方法和正常返回方法之間共享類變量

[英]sharing class variable between async method and normal return method

這是我的課,有一個異步方法和獲取方法

class Webservice
{
    public string token;
    public async void login (string url)
    {
        Console.WriteLine(url);
        var client = new HttpClient();

        // Create the HttpContent for the form to be posted.
        string username = ConfigurationSettings.AppSettings["email"];
        string password = ConfigurationSettings.AppSettings["password"];

        var requestContent = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string, string>("email", username),
                new KeyValuePair<string, string>("password", password),
        });

        // Get the response.
        HttpResponseMessage response = await client.PostAsync(url, requestContent);

        // Get the response content.
        HttpContent responseContent = response.Content;

        // Get the stream of the content.
        using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
        {
            // Write the output.
            //Console.WriteLine(await reader.ReadToEndAsync());
            token = await reader.ReadToEndAsync();

        }
    }


    public string getToken (string url)
    {
        this.login(url);
        Console.WriteLine(token);
        return token+"abc";
    }

令牌=等待reader.ReadToEndAsync(); 無法設置類變量或返回getToken之后設置,有人知道如何處理這種情況嗎?

通過致電:

this.login(url);

您正在觸發並忘記了異步調用。

您需要使包含函數異步並等待login調用完成

public async Task<string> getToken (string url)
{
    await this.login(url);
    Console.WriteLine(token);
    return token+"abc";
}

不要使用this.login(url).Wait()

最后

public async void login (string url)

async void用於事件處理程序,應該是這樣的:

public async Task login (string url)

恕我直言

我相信這堂課的職責太多了。 它不應該用於檢索和存儲令牌。 可以假設您的應用程序中有某種緩存層(可能只是內存)。

因此,我更喜歡這樣的邏輯:

if (string.IsNullOrWhiteSpace(this.cache[TOKEN_KEY])) {
   this.cache[TOKEN_KEY] = await this.webservice.login(url);
}

// use the this.cache[TOKEN_KEY] here...
await this.anotherService.MakeRequest(this.cache[TOKEN_KEY]);

cache可能只是帶有字典的單例類。

現在,新的Task<string> login(string url)方法將在底部返回令牌,而不僅僅是設置私有字段:

return await responseContent.ReadAsStringAsync();

如果需要,這種邏輯將使您更輕松地在登錄名中及其周圍添加層,而又無需使代碼難以推理。

暫無
暫無

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

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