Merge pull request #994 from Bond-009/tasks

Remove Tasks wrapped in a Task
This commit is contained in:
Anthony Lavado 2019-06-05 01:11:25 -04:00 committed by GitHub
commit 256f44a870
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 53 additions and 79 deletions

View File

@ -805,19 +805,15 @@ namespace Emby.Server.Implementations.HttpServer
Logger.LogDebug("Websocket message received: {0}", result.MessageType); Logger.LogDebug("Websocket message received: {0}", result.MessageType);
var tasks = _webSocketListeners.Select(i => Task.Run(async () => IEnumerable<Task> GetTasks()
{ {
try foreach (var x in _webSocketListeners)
{ {
await i.ProcessMessage(result).ConfigureAwait(false); yield return x.ProcessMessageAsync(result);
} }
catch (Exception ex) }
{
Logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty);
}
}));
return Task.WhenAll(tasks); return Task.WhenAll(GetTasks());
} }
public void Dispose() public void Dispose()

View File

@ -89,10 +89,8 @@ namespace Emby.Server.Implementations.Session
/// </summary> /// </summary>
/// <param name="message">The message.</param> /// <param name="message">The message.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
public Task ProcessMessage(WebSocketMessageInfo message) public Task ProcessMessageAsync(WebSocketMessageInfo message)
{ => Task.CompletedTask;
return Task.CompletedTask;
}
private void EnsureController(SessionInfo session, IWebSocketConnection connection) private void EnsureController(SessionInfo session, IWebSocketConnection connection)
{ {

View File

@ -86,8 +86,7 @@ namespace Emby.Server.Implementations.SocketSharp
else else
{ {
// We use a substream, as in 2.x we will support large uploads streamed to disk, // We use a substream, as in 2.x we will support large uploads streamed to disk,
var sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length); files[e.Name] = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
files[e.Name] = sub;
} }
} }
} }
@ -374,7 +373,7 @@ namespace Emby.Server.Implementations.SocketSharp
var elem = new Element(); var elem = new Element();
ReadOnlySpan<char> header; ReadOnlySpan<char> header;
while ((header = ReadHeaders().AsSpan()) != null) while ((header = ReadLine().AsSpan()).Length != 0)
{ {
if (header.StartsWith("Content-Disposition:".AsSpan(), StringComparison.OrdinalIgnoreCase)) if (header.StartsWith("Content-Disposition:".AsSpan(), StringComparison.OrdinalIgnoreCase))
{ {
@ -513,17 +512,6 @@ namespace Emby.Server.Implementations.SocketSharp
return false; return false;
} }
private string ReadHeaders()
{
string s = ReadLine();
if (s.Length == 0)
{
return null;
}
return s;
}
private static bool CompareBytes(byte[] orig, byte[] other) private static bool CompareBytes(byte[] orig, byte[] other)
{ {
for (int i = orig.Length - 1; i >= 0; i--) for (int i = orig.Length - 1; i >= 0; i--)

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Linq;
using System.Text; using System.Text;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
using MediaBrowser.Model.Services; using MediaBrowser.Model.Services;
@ -296,27 +297,28 @@ namespace Emby.Server.Implementations.SocketSharp
{ {
get get
{ {
if (httpFiles == null) if (httpFiles != null)
{ {
if (files == null) return httpFiles;
{ }
return httpFiles = Array.Empty<IHttpFile>();
}
httpFiles = new IHttpFile[files.Count]; if (files == null)
var i = 0; {
foreach (var pair in files) return httpFiles = Array.Empty<IHttpFile>();
}
var values = files.Values;
httpFiles = new IHttpFile[values.Count];
for (int i = 0; i < values.Count; i++)
{
var reqFile = values.ElementAt(i);
httpFiles[i] = new HttpFile
{ {
var reqFile = pair.Value; ContentType = reqFile.ContentType,
httpFiles[i] = new HttpFile ContentLength = reqFile.ContentLength,
{ FileName = reqFile.FileName,
ContentType = reqFile.ContentType, InputStream = reqFile.InputStream,
ContentLength = reqFile.ContentLength, };
FileName = reqFile.FileName,
InputStream = reqFile.InputStream,
};
i++;
}
} }
return httpFiles; return httpFiles;

View File

@ -36,7 +36,7 @@ namespace Jellyfin.Server
private static bool _restartOnShutdown; private static bool _restartOnShutdown;
private static IConfiguration appConfig; private static IConfiguration appConfig;
public static async Task Main(string[] args) public static Task Main(string[] args)
{ {
// For backwards compatibility. // For backwards compatibility.
// Modify any input arguments now which start with single-hyphen to POSIX standard // Modify any input arguments now which start with single-hyphen to POSIX standard
@ -50,8 +50,8 @@ namespace Jellyfin.Server
} }
// Parse the command line arguments and either start the app or exit indicating error // Parse the command line arguments and either start the app or exit indicating error
await Parser.Default.ParseArguments<StartupOptions>(args) return Parser.Default.ParseArguments<StartupOptions>(args)
.MapResult(StartApp, _ => Task.CompletedTask).ConfigureAwait(false); .MapResult(StartApp, _ => Task.CompletedTask);
} }
public static void Shutdown() public static void Shutdown()

View File

@ -999,19 +999,16 @@ namespace MediaBrowser.Api.Library
/// Posts the specified request. /// Posts the specified request.
/// </summary> /// </summary>
/// <param name="request">The request.</param> /// <param name="request">The request.</param>
public void Post(RefreshLibrary request) public async Task Post(RefreshLibrary request)
{ {
Task.Run(() => try
{ {
try await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
{ }
_libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None); catch (Exception ex)
} {
catch (Exception ex) Logger.LogError(ex, "Error refreshing library");
{ }
Logger.LogError(ex, "Error refreshing library");
}
});
} }
/// <summary> /// <summary>

View File

@ -57,7 +57,7 @@ namespace MediaBrowser.Controller.Net
/// </summary> /// </summary>
/// <param name="message">The message.</param> /// <param name="message">The message.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
public Task ProcessMessage(WebSocketMessageInfo message) public Task ProcessMessageAsync(WebSocketMessageInfo message)
{ {
if (message == null) if (message == null)
{ {
@ -74,7 +74,7 @@ namespace MediaBrowser.Controller.Net
Stop(message); Stop(message);
} }
return Task.FromResult(true); return Task.CompletedTask;
} }
protected readonly CultureInfo UsCulture = new CultureInfo("en-US"); protected readonly CultureInfo UsCulture = new CultureInfo("en-US");

View File

@ -12,6 +12,6 @@ namespace MediaBrowser.Controller.Net
/// </summary> /// </summary>
/// <param name="message">The message.</param> /// <param name="message">The message.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
Task ProcessMessage(WebSocketMessageInfo message); Task ProcessMessageAsync(WebSocketMessageInfo message);
} }
} }

View File

@ -23,8 +23,6 @@ namespace Rssdp.Infrastructure
#region Public Methods #region Public Methods
private static byte[] EmptyByteArray = new byte[]{};
/// <summary> /// <summary>
/// Parses the <paramref name="data"/> provided into either a <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object. /// Parses the <paramref name="data"/> provided into either a <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object.
/// </summary> /// </summary>
@ -46,7 +44,7 @@ namespace Rssdp.Infrastructure
if (data.Length == 0) throw new ArgumentException("data cannot be an empty string.", nameof(data)); if (data.Length == 0) throw new ArgumentException("data cannot be an empty string.", nameof(data));
if (!LineTerminators.Any(data.Contains)) throw new ArgumentException("data is not a valid request, it does not contain any CRLF/LF terminators.", nameof(data)); if (!LineTerminators.Any(data.Contains)) throw new ArgumentException("data is not a valid request, it does not contain any CRLF/LF terminators.", nameof(data));
using (var retVal = new ByteArrayContent(EmptyByteArray)) using (var retVal = new ByteArrayContent(Array.Empty<byte>()))
{ {
var lines = data.Split(LineTerminators, StringSplitOptions.None); var lines = data.Split(LineTerminators, StringSplitOptions.None);
@ -209,4 +207,4 @@ namespace Rssdp.Infrastructure
#endregion #endregion
} }
} }

View File

@ -355,7 +355,7 @@ namespace Rssdp.Infrastructure
{ {
var socket = _SocketFactory.CreateUdpMulticastSocket(SsdpConstants.MulticastLocalAdminAddress, _MulticastTtl, SsdpConstants.MulticastPort); var socket = _SocketFactory.CreateUdpMulticastSocket(SsdpConstants.MulticastLocalAdminAddress, _MulticastTtl, SsdpConstants.MulticastPort);
ListenToSocket(socket); _ = ListenToSocketInternal(socket);
return socket; return socket;
} }
@ -389,19 +389,12 @@ namespace Rssdp.Infrastructure
foreach (var socket in sockets) foreach (var socket in sockets)
{ {
ListenToSocket(socket); _ = ListenToSocketInternal(socket);
} }
return sockets; return sockets;
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capturing task to local variable removes compiler warning, task is not otherwise required.")]
private void ListenToSocket(ISocket socket)
{
// Tasks are captured to local variables even if we don't use them just to avoid compiler warnings.
var t = Task.Run(() => ListenToSocketInternal(socket));
}
private async Task ListenToSocketInternal(ISocket socket) private async Task ListenToSocketInternal(ISocket socket)
{ {
var cancelled = false; var cancelled = false;
@ -448,10 +441,10 @@ namespace Rssdp.Infrastructure
private void ProcessMessage(string data, IpEndPointInfo endPoint, IpAddressInfo receivedOnLocalIpAddress) private void ProcessMessage(string data, IpEndPointInfo endPoint, IpAddressInfo receivedOnLocalIpAddress)
{ {
//Responses start with the HTTP version, prefixed with HTTP/ while // Responses start with the HTTP version, prefixed with HTTP/ while
//requests start with a method which can vary and might be one we haven't // requests start with a method which can vary and might be one we haven't
//seen/don't know. We'll check if this message is a request or a response // seen/don't know. We'll check if this message is a request or a response
//by checking for the HTTP/ prefix on the start of the message. // by checking for the HTTP/ prefix on the start of the message.
if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase)) if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
{ {
HttpResponseMessage responseMessage = null; HttpResponseMessage responseMessage = null;
@ -465,7 +458,9 @@ namespace Rssdp.Infrastructure
} }
if (responseMessage != null) if (responseMessage != null)
{
OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress); OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress);
}
} }
else else
{ {