0 .net c# 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 方法之后,如果我使用等待此 vs 崩溃并关闭,则不要填充 publicToken。你有这个想法吗?
仅仅是因为在为变量赋值TryForGetToken之前完成。您不是在等待从 TryForLogin 方法返回的任务。
你应该重写为然后TryForLoginpublicToken
TryForGetTokenasync Task<string>await TryForLogin()