madaxe2020
Well-known member
- Joined
- Sep 7, 2020
- Messages
- 50
- Programming Experience
- 5-10
I'm downloading files from a Jira Task, and while debugging my code exists before the file is downloaded as a result the thread is exiting and the file is not downloading. i added the do loop and this gives enough time for the file to download, but I don't like it.
how can i stop the code form completing before all awaited threads have finished?
thanks
Madaxe
how can i stop the code form completing before all awaited threads have finished?
thanks
Madaxe
Download Helper:
public bool DownloadAttachment(string attachmentId, string folderPath)
{
Attachment? attachment = (from x in _attachments where x.id == attachmentId select x).FirstOrDefault()??null;
if (attachment != null)
{
string filePath = string.Concat(folderPath, Path.DirectorySeparatorChar, attachment.filename);
var bob = EnvironmentMangerHTTPClient.DownloadTaskAttachmentAsync(attachmentId, filePath);
var startTime = DateTime.UtcNow;
//Allow upto 1 minute before returning false
do
{
if(DateTime.UtcNow - startTime == TimeSpan.FromMinutes(1))
{
return false;
}
} while (File.Exists(filePath)==false);
return true;
}
else
{
return false;
}
}
DownloadAsync:
public static async Task<bool> DownloadTaskAttachmentAsync(string attachmentId, string filePath)
{
if (!String.IsNullOrEmpty(apiKey) && !String.IsNullOrEmpty(username))
{
var returnstatus = await GetAttachment(String.Concat("/rest/api/3/attachment/content/", attachmentId), filePath);
return true;
}
throw new Exception("Environment Variables jiraapikey and jirausername were invalid.");
}
GetAttachment:
private static async Task<bool> GetAttachment(string url, string filePath)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Add("Authorization", $"Basic {credentials}");
var dataStream = await client.GetStreamAsync(url);
string fileToWriteTo = string.Concat(filePath);
using Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create);
{
await dataStream.CopyToAsync(streamToWriteTo);
}
return true;
}
}
catch(Exception ex)
{
Console.Write(ex.ToString());
return false;
}
}
Last edited: