0

I use async method follow this code:

    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();
    }

and

    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();
        }
    }

So after call postJsonAsync method and after that don`t fill publicToken if I use wait for this vs crash and closed. Do you have idea for this ?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Arian Jira
  • 11
  • 4

2 Answers2

6

Simply because the TryForGetToken finishes before TryForLogin assign value to publicToken variable. You are not awaiting Task that is returned from TryForLogin method.

You should rewrite TryForGetToken to be async Task<string> and then await TryForLogin()

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Tomas Chabada
  • 2,869
  • 1
  • 17
  • 18
3

I'm not completely sure what are you asking for but it seems you miss awaiting the TryForLogin method.

 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();
    }
MistGun
  • 162
  • 8