0

I have a property. In getter, I want to call a async method. Please look into code I have also marked comments:-

 public string AuthToken
{
    get
    {
        TimeSpan timediff = App.Locator.Login.TokenExpire_On.ToLocalTime() - DateTime.Now.ToLocalTime();
        if (timediff.TotalMinutes < 55)
            App.Locator.Login.GetRefreshToken();
        // before return the value i want to complete the work of GetRefreshToken(), GetRefreshToken is a async method.
        return AppSettings.GetValueOrDefault<string>(AuthTokenKey, AuthTokenDefault);
    }
    set
    {
        AppSettings.AddOrUpdateValue<string>(AuthTokenKey, value);
    }
}

public async Task GetRefreshToken()
{
    if (string.IsNullOrEmpty(this.AuthToken))
        return;
    AzureRefreshToken refreshToken = await UserProfileService.RefreshToken(this.AuthToken);
    Settings.AuthToken = refreshToken.RefreshToken;
    TokenExpire_On = DateTime.Now.AddHours(1);

}
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Gurpreet Singh
  • 165
  • 4
  • 18
  • 2
    Possible duplicate of [How to call an async method from a getter or setter?](http://stackoverflow.com/questions/6602244/how-to-call-an-async-method-from-a-getter-or-setter) – Sinatr Aug 17 '16 at 12:53
  • Think about your problem a different way: what if nothing calls `AuthToken` until after it's expired? The current property-based solution assumes that a call will be made in that 5-minute window just before it expires. IMO it would be more appropriate to have a refresh loop. – Stephen Cleary Aug 17 '16 at 13:40

1 Answers1

1

Maybe

 if (timediff.TotalMinutes < 55)
        App.Locator.Login.GetRefreshToken().RunSynchronously();

can solve problem?

darkhac
  • 577
  • 4
  • 22