异步等待方法(等待响应)

时间:2020-05-11 07:55:30

标签: c# .net asynchronous async-await memorycache

我使用异步方法遵循以下代码:

    public string TryForGetToken()
    {
        cache = getCache;
        if (!cache.Contains(keyToken))
        {
            CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
            TryForLogin();
            cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddSeconds(expiredTime - 60);
            CacheItem item = new CacheItem(keyToken, publicToken);
            //cache.Add(item, cacheItemPolicy);
            return publicToken;
        }
        else
            return cache.Get(keyToken).ToString();
    }

    public async Task TryForLogin()
    {
        await _semaphore.WaitAsync();
        try
        {
            AuthenticationData authenticationData = new AuthenticationData() { email = "zzzzzz", password = "zzzzzzzz" };
            ResponseResult result = await httpServiceCaller.PostJsonAsync<AuthenticationData, ResponseResult>("http://sample.com/agent/login", authenticationData, new CancellationToken(), "Login");
            publicToken = result.data.token.access_token;
            expiredTime = result.data.token.expires_in;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw;
        }
        finally
        {
            _semaphore.Release();
        }
    }

因此,在调用postJsonAsync方法之后,请勿填充publicToken 如果我使用等待此vs崩溃并关闭。你有这个主意吗?

2 个答案:

答案 0 :(得分:6)

仅是因为TryForGetTokenTryForLogin赋值到publicToken变量之前完成。您没有在等待从TryForLogin方法返回的任务。

您应该将TryForGetToken改写为async Task<string>,然后再写await TryForLogin()

答案 1 :(得分:3)

我不确定您要什么,但似乎您错过了等待TryForLogin方法的时间。

 public async Task<string> TryForGetToken()
    {
        cache = getCache;
        if (!cache.Contains(keyToken))
        {
            CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
            await TryForLogin();
            cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddSeconds(expiredTime - 60);
            CacheItem item = new CacheItem(keyToken, publicToken);
            //cache.Add(item, cacheItemPolicy);
            return publicToken;
        }
        else
            return cache.Get(keyToken).ToString();
    }