I have implemented some code to access an oauth 2.0 protected api. The Unity Engine freezes as soon as I hit "play" button. and I have to close it via Task Manager.
My Code:
public class importFromAPI : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
HttpClient client = new HttpClient();
Task<Token> task = GetElibilityToken(client);
//Token token = task.Result;
}
// Update is called once per frame
void Update()
{
}
// OAuth Stuff
private static async Task<Token> GetElibilityToken(HttpClient client)
{
string baseAddress = @"*REDACTED*/oauth/token";
string grant_type = "client_credentials";
string client_id = "*REDACTED*";
string client_secret = "*REDACTED*";
string audience = "*REDACTED*";
var form = new Dictionary<string, string>
{
{"grant_type", grant_type},
{"client_id", client_id},
{"client_secret", client_secret},
{"audience", audience }
};
HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Debug.Log("Response: " jsonContent);
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
Debug.Log(tok.ToString());
return tok;
}
internal class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
override
public string ToString()
{
return "AccessToken: " AccessToken "; TokenType: " TokenType "; Expires in: " ExpiresIn "; Refresh Token: " RefreshToken;
}
}
}
Removing task.Result from the Start() method stops Unity from freezing on pressing the button, but I want to get the token to access the api afterwards.
Can anyone tell me why Unity freezes?
CodePudding user response:
You need to use the await keyword, something like this:
Token task = await GetElibilityToken(client);
However you need to change the method as well, something like this:
async Task Start()
Actually it's been recommended to use async all the way down always. You can find more information in this topic here.
https://gametorrahod.com/unity-and-async-await/
EDIT: Based on the comments, it seems we are not allowed to change or redefine the Unity's Start to be async Task, so in this case I would still use the async void, despite the fact that it is not been recommended https://docs.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming
async void Start()
