【发布时间】:2022-01-14 06:08:44
【问题描述】:
我已经实现了一些代码来访问受 oauth 2.0 保护的 api。一旦我点击“播放”按钮,Unity 引擎就会冻结。我必须通过任务管理器关闭它。
我的代码:
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;
}
}
}
从 Start() 方法中删除 task.Result 会阻止 Unity 在按下按钮时冻结,但我想获取令牌以访问 api。
谁能告诉我为什么 Unity 会死机?
【问题讨论】:
-
Can anyone tell me why Unity freezes?- 因为它是deadlocks。 -
这不是死锁,线程只是被阻塞直到任务完成。
标签: c# unity3d async-await