Lower the amount of running tasks

This commit is contained in:
Bond_009 2019-02-24 03:16:19 +01:00 committed by Bond-009
parent 5024c52c60
commit 2696ac5eac
10 changed files with 53 additions and 81 deletions

View File

@ -11,7 +11,6 @@ using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Net;
using Emby.Server.Implementations.Services;
using Emby.Server.Implementations.SocketSharp;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
@ -823,19 +822,15 @@ namespace Emby.Server.Implementations.HttpServer
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()

View File

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

View File

@ -86,8 +86,7 @@ namespace Emby.Server.Implementations.SocketSharp
else
{
// 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] = sub;
files[e.Name] = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
}
}
}
@ -374,7 +373,7 @@ namespace Emby.Server.Implementations.SocketSharp
var elem = new Element();
ReadOnlySpan<char> header;
while ((header = ReadHeaders().AsSpan()) != null)
while ((header = ReadLine().AsSpan()).Length != 0)
{
if (header.StartsWith("Content-Disposition:".AsSpan(), StringComparison.OrdinalIgnoreCase))
{
@ -513,17 +512,6 @@ namespace Emby.Server.Implementations.SocketSharp
return false;
}
private string ReadHeaders()
{
string s = ReadLine();
if (s.Length == 0)
{
return null;
}
return s;
}
private static bool CompareBytes(byte[] orig, byte[] other)
{
for (int i = orig.Length - 1; i >= 0; i--)

View File

@ -3,8 +3,8 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
@ -474,27 +474,28 @@ namespace Emby.Server.Implementations.SocketSharp
{
get
{
if (httpFiles == null)
if (httpFiles != null)
{
if (files == null)
{
return httpFiles = Array.Empty<IHttpFile>();
}
return httpFiles;
}
httpFiles = new IHttpFile[files.Count];
var i = 0;
foreach (var pair in files)
if (files == null)
{
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;
httpFiles[i] = new HttpFile
{
ContentType = reqFile.ContentType,
ContentLength = reqFile.ContentLength,
FileName = reqFile.FileName,
InputStream = reqFile.InputStream,
};
i++;
}
ContentType = reqFile.ContentType,
ContentLength = reqFile.ContentLength,
FileName = reqFile.FileName,
InputStream = reqFile.InputStream,
};
}
return httpFiles;

View File

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

View File

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

View File

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

View File

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

View File

@ -23,8 +23,6 @@ namespace Rssdp.Infrastructure
#region Public Methods
private static byte[] EmptyByteArray = new byte[]{};
/// <summary>
/// Parses the <paramref name="data"/> provided into either a <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object.
/// </summary>
@ -46,7 +44,7 @@ namespace Rssdp.Infrastructure
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));
using (var retVal = new ByteArrayContent(EmptyByteArray))
using (var retVal = new ByteArrayContent(Array.Empty<byte>()))
{
var lines = data.Split(LineTerminators, StringSplitOptions.None);
@ -209,4 +207,4 @@ namespace Rssdp.Infrastructure
#endregion
}
}
}

View File

@ -355,7 +355,7 @@ namespace Rssdp.Infrastructure
{
var socket = _SocketFactory.CreateUdpMulticastSocket(SsdpConstants.MulticastLocalAdminAddress, _MulticastTtl, SsdpConstants.MulticastPort);
ListenToSocket(socket);
_ = ListenToSocketInternal(socket);
return socket;
}
@ -389,19 +389,12 @@ namespace Rssdp.Infrastructure
foreach (var socket in sockets)
{
ListenToSocket(socket);
_ = ListenToSocketInternal(socket);
}
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)
{
var cancelled = false;
@ -448,10 +441,10 @@ namespace Rssdp.Infrastructure
private void ProcessMessage(string data, IpEndPointInfo endPoint, IpAddressInfo receivedOnLocalIpAddress)
{
//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
//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.
// 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
// 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.
if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
{
HttpResponseMessage responseMessage = null;
@ -465,7 +458,9 @@ namespace Rssdp.Infrastructure
}
if (responseMessage != null)
{
OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress);
}
}
else
{