Question by
nfAbondano · Jun 02 at 10:59 PM ·
optimizationcoroutinesasyncasynchronous
How to properly call Async Task
I have this async task, and I am calling it with a coroutine, but it stops briefly the game and I want it to run on background so it DOESN'T stop the main thread at all. This is the coroutine that calls the async task. I don't know what to do to run it smoothly. Please help and thank you!
// Coroutine that calls the async method GetNewSong
IEnumerator AsyncDownloadSong()
{
downloadBtn.interactable = false;
deleteBtn.interactable = true;
customManager.GetNewSong(s3File);
yield return new WaitForSeconds(0.1f);
}
// Async task that awaits async method
public async Task GetNewSong(string pFile)
{
await awsManager.GetZip(pFile);
}
// Async task that calls and AWS method.
// The important thing is that is async, the aws logic is fine and saves
// the file where is supposed to be
public async Task GetZip(string pFile)
{
string folder = "Assets/Audio/Custom/";
try
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = S3Bucket,
Key = pFile
};
using (GetObjectResponse response = await S3Client.GetObjectAsync(request))
using (Stream responseStream = response.ResponseStream)
{
string title = response.Metadata["x-amz-meta-title"]; // Assume you have "title" as medata added to the object.
string contentType = response.Headers["Content-Type"];
Debug.Log("Object metadata, Title: " + title);
Debug.Log("Content type: " + contentType);
if (responseStream != null)
{
using (BinaryReader bReader = new BinaryReader(response.ResponseStream))
{
byte[] buffer = bReader.ReadBytes((int)response.ResponseStream.Length);
File.WriteAllBytes(folder + S3SampleFile, buffer);
Debug.Log("Writed all bytes");
StartCoroutine(customSongsManager.ReadDownloadedSong(folder + S3SampleFile));
}
}
}
}
catch (AmazonS3Exception e)
{
// If bucket or object does not exist
Debug.Log("Error encountered ***. Message:"+ e.Message + " when reading object");
}
catch (Exception e)
{
Debug.Log("Unknown encountered on server. Message:"+ e.Message + " when reading object");
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613061313im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I preload multiple scenes? 0 Answers
Unity C# Punching Coroutine not completing 0 Answers
Unity, WebClient, Upload, Async and Threads. 0 Answers
Async Scene Load for Gear VR 0 Answers