Properly dispose Tasks

This commit is contained in:
Bond_009 2019-01-29 21:39:12 +01:00
parent 66eabcdd39
commit 95ee3c72e3
3 changed files with 64 additions and 68 deletions

View File

@ -462,7 +462,7 @@ namespace MediaBrowser.Api
Logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
KillTranscodingJob(job, true, path => true);
KillTranscodingJob(job, true, path => true).GetAwaiter().GetResult();
}
/// <summary>
@ -472,9 +472,9 @@ namespace MediaBrowser.Api
/// <param name="playSessionId">The play session identifier.</param>
/// <param name="deleteFiles">The delete files.</param>
/// <returns>Task.</returns>
internal void KillTranscodingJobs(string deviceId, string playSessionId, Func<string, bool> deleteFiles)
internal Task KillTranscodingJobs(string deviceId, string playSessionId, Func<string, bool> deleteFiles)
{
KillTranscodingJobs(j =>
return KillTranscodingJobs(j =>
{
if (!string.IsNullOrWhiteSpace(playSessionId))
{
@ -492,7 +492,7 @@ namespace MediaBrowser.Api
/// <param name="killJob">The kill job.</param>
/// <param name="deleteFiles">The delete files.</param>
/// <returns>Task.</returns>
private void KillTranscodingJobs(Func<TranscodingJob, bool> killJob, Func<string, bool> deleteFiles)
private Task KillTranscodingJobs(Func<TranscodingJob, bool> killJob, Func<string, bool> deleteFiles)
{
var jobs = new List<TranscodingJob>();
@ -505,22 +505,27 @@ namespace MediaBrowser.Api
if (jobs.Count == 0)
{
return;
return Task.CompletedTask;
}
IEnumerable<Task> GetKillJobs()
{
foreach (var job in jobs)
{
KillTranscodingJob(job, false, deleteFiles);
yield return KillTranscodingJob(job, false, deleteFiles);
}
}
return Task.WhenAll(GetKillJobs());
}
/// <summary>
/// Kills the transcoding job.
/// </summary>
/// <param name="job">The job.</param>
/// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
/// <param name="delete">The delete.</param>
private async void KillTranscodingJob(TranscodingJob job, bool closeLiveStream, Func<string, bool> delete)
private async Task KillTranscodingJob(TranscodingJob job, bool closeLiveStream, Func<string, bool> delete)
{
job.DisposeKillTimer();
@ -577,7 +582,7 @@ namespace MediaBrowser.Api
if (delete(job.Path))
{
DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
await DeletePartialStreamFiles(job.Path, job.Type, 0, 1500).ConfigureAwait(false);
}
if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
@ -588,12 +593,12 @@ namespace MediaBrowser.Api
}
catch (Exception ex)
{
Logger.LogError(ex, "Error closing live stream for {path}", job.Path);
Logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
}
}
}
private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
{
if (retryCount >= 10)
{
@ -623,7 +628,7 @@ namespace MediaBrowser.Api
{
Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
}
catch (Exception ex)
{
@ -650,8 +655,7 @@ namespace MediaBrowser.Api
var name = Path.GetFileNameWithoutExtension(outputFilePath);
var filesToDelete = _fileSystem.GetFilePaths(directory)
.Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
.ToList();
.Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
Exception e = null;

View File

@ -366,9 +366,9 @@ namespace MediaBrowser.Api.UserLibrary
/// Posts the specified request.
/// </summary>
/// <param name="request">The request.</param>
public void Delete(OnPlaybackStopped request)
public Task Delete(OnPlaybackStopped request)
{
Post(new ReportPlaybackStopped
return Post(new ReportPlaybackStopped
{
ItemId = new Guid(request.Id),
PositionTicks = request.PositionTicks,
@ -379,20 +379,18 @@ namespace MediaBrowser.Api.UserLibrary
});
}
public void Post(ReportPlaybackStopped request)
public async Task Post(ReportPlaybackStopped request)
{
Logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", request.PlaySessionId ?? string.Empty);
if (!string.IsNullOrWhiteSpace(request.PlaySessionId))
{
ApiEntryPoint.Instance.KillTranscodingJobs(_authContext.GetAuthorizationInfo(Request).DeviceId, request.PlaySessionId, s => true);
await ApiEntryPoint.Instance.KillTranscodingJobs(_authContext.GetAuthorizationInfo(Request).DeviceId, request.PlaySessionId, s => true);
}
request.SessionId = GetSession(_sessionContext).Id;
var task = _sessionManager.OnPlaybackStopped(request);
Task.WaitAll(task);
await _sessionManager.OnPlaybackStopped(request);
}
/// <summary>
@ -403,10 +401,10 @@ namespace MediaBrowser.Api.UserLibrary
{
var task = MarkUnplayed(request);
return ToOptimizedResult(task.Result);
return ToOptimizedResult(task);
}
private async Task<UserItemDataDto> MarkUnplayed(MarkUnplayedItem request)
private UserItemDataDto MarkUnplayed(MarkUnplayedItem request)
{
var user = _userManager.GetUserById(request.UserId);

View File

@ -76,7 +76,9 @@ namespace MediaBrowser.MediaEncoding.Encoder
var commandLineArgs = GetCommandLineArguments(encodingJob);
Process process = Process.Start(new ProcessStartInfo
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
@ -91,9 +93,9 @@ namespace MediaBrowser.MediaEncoding.Encoder
Arguments = commandLineArgs,
ErrorDialog = false
});
process.EnableRaisingEvents = true;
},
EnableRaisingEvents = true
};
var workingDirectory = GetWorkingDirectory(options);
if (!string.IsNullOrWhiteSpace(workingDirectory))
@ -132,50 +134,42 @@ namespace MediaBrowser.MediaEncoding.Encoder
cancellationToken.Register(async () => await Cancel(process, encodingJob));
// MUST read both stdout and stderr asynchronously or a deadlock may occur
//process.BeginOutputReadLine();
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream);
// Wait for the file to or for the process to stop
Task file = WaitForFileAsync(encodingJob.OutputFilePath);
await Task.WhenAny(encodingJob.TaskCompletionSource.Task, file).ConfigureAwait(false);
Logger.LogInformation("test0");
if (File.Exists(encodingJob.OutputFilePath))
{
return encodingJob;
}
public static Task WaitForFileAsync(string path)
{
if (File.Exists(path))
{
return Task.CompletedTask;
}
Logger.LogInformation("test1");
using (var watcher = new FileSystemWatcher(Path.GetDirectoryName(encodingJob.OutputFilePath)))
{
var tcs = new TaskCompletionSource<bool>();
FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(path));
string fileName = Path.GetFileName(encodingJob.OutputFilePath);
watcher.Created += (s, e) =>
{
if (e.Name == Path.GetFileName(path))
if (e.Name == fileName)
{
watcher.Dispose();
tcs.TrySetResult(true);
}
};
watcher.Renamed += (s, e) =>
{
if (e.Name == Path.GetFileName(path))
{
watcher.Dispose();
tcs.TrySetResult(true);
}
};
watcher.EnableRaisingEvents = true;
return tcs.Task;
Logger.LogInformation("test2");
// Wait for the file to or for the process to stop
await Task.WhenAny(encodingJob.TaskCompletionSource.Task, tcs.Task).ConfigureAwait(false);
Logger.LogInformation("test3");
return encodingJob;
}
}
private async Task Cancel(Process process, EncodingJob job)