public async Task <IJobArtifactCacheSession> GetOrAddArtifacts(IJob job) { return(await Task.Run <IJobArtifactCacheSession>(async() => { await _semaphore.WaitAsync(); var jobPath = Path.Combine(_options.ArtifactsCacheDirectory, $"{job.ProjectId}-{job.JobId}"); try { if (Directory.Exists(jobPath)) { _semaphore.Release(); return new JobArtifactSession(jobPath); } } catch (Exception) { _semaphore.Release(); throw; } // No artifacts path exists for this job try { Directory.CreateDirectory(jobPath); try { await job.GetArtifacts(async response => { using (var responseContent = response.Content) { using (var responseStream = await responseContent.ReadAsStreamAsync()) { using (var archive = new ZipArchive(responseStream, ZipArchiveMode.Read)) { archive.ExtractToDirectory(jobPath); } } } }); return new JobArtifactSession(jobPath); } catch (Exception) { Directory.Delete(jobPath, true); throw; } } finally { _semaphore.Release(); } })); }