我已經實作了一些代碼來訪問受 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;
}
}
}
task.Result從方法中洗掉會Start()阻止 Unity 在按下按鈕時凍結,但我想獲取令牌以在之后訪問 api。
誰能告訴我為什么 Unity 會死機?
uj5u.com熱心網友回復:
您需要使用await關鍵字,如下所示:
Token task = await GetElibilityToken(client);
但是,您還需要更改方法,如下所示:
async Task Start()
實際上,建議始終使用 async 。您可以在此處找到有關此主題的更多資訊。
https://gametorrahod.com/unity-and-async-await/
編輯:根據評論,似乎我們不允許將 Unity 更改或重新定義Start為async Task,所以在這種情況下,我仍然會使用async void,盡管不推薦使用https://docs.microsoft.com /en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming
async void Start()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/410965.html
標籤:
上一篇:是否可以在一個按鈕中有兩個點擊事件,然后在另一個之前執行一個?
下一篇:如何平滑地鉗制控制器輸入?
