Does this create a race condition in this class? In the while loop? Only 2 downloads should be allowed concurrently. The calculations work should not be done concurrently (time sensitive). The question is about this code. I know there are other ways to accomplish this like using ConcurrentQueue.
//class setup
public class FileService : IFileService
{
private static Queue<string> fileNamesQueue = new Queue<string>();
private static int concurentDownloads = 0;
private static bool calcBusy = false;
...
//called by a button click event in UI
public async void Download(string fileName)
{
fileNamesQueue.Enqueue(fileName);
while (fileNamesQueue.Count > 0)
{
await Task.Delay(500);
if (concurentDownloads < 2 && !calcBusy)
DownloadItem();
}
}
//beginning of perform download
public async void DownloadItem()
{
concurentDownloads++;
var fileName = string.Empty;
if (fileNamesQueue.Count > 0)
{
fileNamesQueue.TryDequeue(out fileName);
//perform calc work but ensure they are not concurrent
calcBusy = true;
//do calc work
calcBusy = false;
//create download task
...
//concurentDownloads gets decremented after each download completes in a completed event