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); 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> /// <summary>
@ -472,9 +472,9 @@ namespace MediaBrowser.Api
/// <param name="playSessionId">The play session identifier.</param> /// <param name="playSessionId">The play session identifier.</param>
/// <param name="deleteFiles">The delete files.</param> /// <param name="deleteFiles">The delete files.</param>
/// <returns>Task.</returns> /// <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)) if (!string.IsNullOrWhiteSpace(playSessionId))
{ {
@ -492,7 +492,7 @@ namespace MediaBrowser.Api
/// <param name="killJob">The kill job.</param> /// <param name="killJob">The kill job.</param>
/// <param name="deleteFiles">The delete files.</param> /// <param name="deleteFiles">The delete files.</param>
/// <returns>Task.</returns> /// <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>(); var jobs = new List<TranscodingJob>();
@ -505,13 +505,18 @@ namespace MediaBrowser.Api
if (jobs.Count == 0) if (jobs.Count == 0)
{ {
return; return Task.CompletedTask;
} }
foreach (var job in jobs) IEnumerable<Task> GetKillJobs()
{ {
KillTranscodingJob(job, false, deleteFiles); foreach (var job in jobs)
{
yield return KillTranscodingJob(job, false, deleteFiles);
}
} }
return Task.WhenAll(GetKillJobs());
} }
/// <summary> /// <summary>
@ -520,7 +525,7 @@ namespace MediaBrowser.Api
/// <param name="job">The job.</param> /// <param name="job">The job.</param>
/// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param> /// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
/// <param name="delete">The delete.</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(); job.DisposeKillTimer();
@ -577,7 +582,7 @@ namespace MediaBrowser.Api
if (delete(job.Path)) 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)) if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
@ -588,12 +593,12 @@ namespace MediaBrowser.Api
} }
catch (Exception ex) 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) if (retryCount >= 10)
{ {
@ -623,7 +628,7 @@ namespace MediaBrowser.Api
{ {
Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); 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) catch (Exception ex)
{ {
@ -650,8 +655,7 @@ namespace MediaBrowser.Api
var name = Path.GetFileNameWithoutExtension(outputFilePath); var name = Path.GetFileNameWithoutExtension(outputFilePath);
var filesToDelete = _fileSystem.GetFilePaths(directory) var filesToDelete = _fileSystem.GetFilePaths(directory)
.Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1) .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
.ToList();
Exception e = null; Exception e = null;

View file

@ -366,9 +366,9 @@ namespace MediaBrowser.Api.UserLibrary
/// Posts the specified request. /// Posts the specified request.
/// </summary> /// </summary>
/// <param name="request">The request.</param> /// <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), ItemId = new Guid(request.Id),
PositionTicks = request.PositionTicks, 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); Logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", request.PlaySessionId ?? string.Empty);
if (!string.IsNullOrWhiteSpace(request.PlaySessionId)) 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; request.SessionId = GetSession(_sessionContext).Id;
var task = _sessionManager.OnPlaybackStopped(request); await _sessionManager.OnPlaybackStopped(request);
Task.WaitAll(task);
} }
/// <summary> /// <summary>
@ -403,10 +401,10 @@ namespace MediaBrowser.Api.UserLibrary
{ {
var task = MarkUnplayed(request); 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); var user = _userManager.GetUserById(request.UserId);

View file

@ -76,24 +76,26 @@ namespace MediaBrowser.MediaEncoding.Encoder
var commandLineArgs = GetCommandLineArguments(encodingJob); var commandLineArgs = GetCommandLineArguments(encodingJob);
Process process = Process.Start(new ProcessStartInfo Process process = new Process
{ {
WindowStyle = ProcessWindowStyle.Hidden, StartInfo = new ProcessStartInfo
CreateNoWindow = true, {
UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false,
// Must consume both stdout and stderr or deadlocks may occur // Must consume both stdout and stderr or deadlocks may occur
//RedirectStandardOutput = true, //RedirectStandardOutput = true,
RedirectStandardError = true, RedirectStandardError = true,
RedirectStandardInput = true, RedirectStandardInput = true,
FileName = MediaEncoder.EncoderPath, FileName = MediaEncoder.EncoderPath,
Arguments = commandLineArgs, Arguments = commandLineArgs,
ErrorDialog = false ErrorDialog = false
}); },
EnableRaisingEvents = true
process.EnableRaisingEvents = true; };
var workingDirectory = GetWorkingDirectory(options); var workingDirectory = GetWorkingDirectory(options);
if (!string.IsNullOrWhiteSpace(workingDirectory)) if (!string.IsNullOrWhiteSpace(workingDirectory))
@ -132,50 +134,42 @@ namespace MediaBrowser.MediaEncoding.Encoder
cancellationToken.Register(async () => await Cancel(process, encodingJob)); 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 // 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); new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream);
// Wait for the file to or for the process to stop Logger.LogInformation("test0");
Task file = WaitForFileAsync(encodingJob.OutputFilePath);
await Task.WhenAny(encodingJob.TaskCompletionSource.Task, file).ConfigureAwait(false);
return encodingJob; if (File.Exists(encodingJob.OutputFilePath))
}
public static Task WaitForFileAsync(string path)
{
if (File.Exists(path))
{ {
return Task.CompletedTask; return encodingJob;
} }
var tcs = new TaskCompletionSource<bool>(); Logger.LogInformation("test1");
FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(path));
watcher.Created += (s, e) => using (var watcher = new FileSystemWatcher(Path.GetDirectoryName(encodingJob.OutputFilePath)))
{ {
if (e.Name == Path.GetFileName(path)) var tcs = new TaskCompletionSource<bool>();
string fileName = Path.GetFileName(encodingJob.OutputFilePath);
watcher.Created += (s, e) =>
{ {
watcher.Dispose(); if (e.Name == fileName)
tcs.TrySetResult(true); {
} tcs.TrySetResult(true);
}; }
};
watcher.Renamed += (s, e) => watcher.EnableRaisingEvents = true;
{
if (e.Name == Path.GetFileName(path))
{
watcher.Dispose();
tcs.TrySetResult(true);
}
};
watcher.EnableRaisingEvents = true; Logger.LogInformation("test2");
return tcs.Task; // 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) private async Task Cancel(Process process, EncodingJob job)