我使用异步方法遵循以下代码:
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崩溃并关闭。你有这个主意吗?
答案 0 :(得分:6)
仅是因为TryForGetToken
在TryForLogin
赋值到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();
}