c# set timeout for multipartReader.ReadNextSectionAsync()

Viewed 1308

I'm using C# .net core to read upload data from multipart post user sending multiple files. How can I prevent use waiting infinite after read last file in

try
{
  var cancellationTokenSource = new CancellationTokenSource();
  cancellationTokenSource.CancelAfter(1000);
  section = await multipartReader.ReadNextSectionAsync(cancellationTokenSource.Token);
}
catch (Exception ex)
{
  throw;
}

Altough I've set cancelationToken for 1 second but it goes infinite, and won't go to next line if I will send another request.

public static async Task<HttpRequest> FromHttpContextAsync(HttpContext httpContext)
        {
            bool multipart = false;
            HttpRequest retVal = new HttpRequest(httpContext);
            var sb = new StringBuilder();         
            var sr = new StreamReader(httpContext.Stream, Encoding.UTF8);
            {
                var line1 = await sr.ReadLineAsync();
                sb.AppendLine(line1);
                var Line1Parts = (line1).Split(' ');
                retVal.Methode = Line1Parts[0].ToLower();
                retVal.RawUrl = System.Net.WebUtility.UrlDecode(Line1Parts[1]).Replace("&amp;", "&");
                var urlPart = retVal.RawUrl.Split('?');
                retVal.Url = urlPart[0];
                if (urlPart.Length > 1)
                {
                    foreach (var part in urlPart[1].Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        var tmp = part.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                        try
                        {
                            retVal.QueryStrings.Add(tmp[0], tmp[1]);
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            string line = await sr.ReadLineAsync();
            sb.AppendLine(line);
            int contentLength = 0;
            while (!string.IsNullOrEmpty(line))
            {
                var tmp = line.Split(':');
                var key = tmp[0].Trim().ToLower();
                retVal.Header.Add(new KeyValuePair<string, string>(tmp[0], tmp[1]));

                switch (key)
                {

                    case "cookie":
                        {

                            foreach (var part in tmp[1].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                var pares = part.Split('=');
                                if (pares.Length == 2)
                                {
                                    retVal.Cookies.Add(new KeyValuePair<string, string>(pares[0], pares[1]));
                                }
                            }
                            break;
                        }
                    case "content-length":
                        {
                            contentLength = int.Parse(tmp[1]);
                            break;
                        }
                }
                line = await sr.ReadLineAsync();
                sb.AppendLine(line);
            }
if (sb.ToString().Contains("Content-Type: multipart/form-data"))
{
  string boundary = FindBoundary(sb.ToString());
  MultipartReader multipartReader = new MultipartReader(boundary, httpContext.Stream);
  var section = await multipartReader.ReadNextSectionAsync();
  while (section != null)
  {
    // process each image
    const int chunkSize = 1024;
    var buffer = new byte[chunkSize];
    var bytesRead = 0;
    var fileName = GetFileName(section.ContentDisposition);

    using (var stream = new MemoryStream())
    {
      do
      {
        try
        {
          bytesRead = await section.Body.ReadAsync(buffer, 0, buffer.Length);
        }
        catch (Exception ex)
        {
          Console.Write(ex);
        }

        stream.Write(buffer, 0, bytesRead);
      } while (bytesRead > 0);
      retVal.Files.Add(new Tuple<string, string, byte[]>("", fileName, stream.ToArray()));
    }

    try
    {
      var cancellationTokenSource = new CancellationTokenSource();
      cancellationTokenSource.CancelAfter(1000);
      section = await multipartReader.ReadNextSectionAsync(cancellationTokenSource.Token);
    }
    catch (Exception ex)
    {
      throw;
    }


  }
  foreach (var file in retVal.Files)
  {
    File.WriteAllBytes("d:\\" + file.Item2, file.Item3);
  }
}

HttpContext is inline class of this project and this is the source of HttpContext :

public class HttpContext
    {
        public HttpRequest Request { get; private set; }
        public HttpResponse Response { get; private set; }
        public Stream Stream { private set; get; }
        private HttpContext(Stream networkStream)
        {
            Stream = networkStream;
        }

        public async static Task<HttpContext> FromHttpContextAsync(Stream networkStream)
        {
            var retVal = new HttpContext(networkStream);
            retVal.Request = await HttpRequest.FromHttpContextAsync(retVal);
            retVal.Response = HttpResponse.FromHttpContext(retVal);
            return retVal;
        }
    }
1 Answers

While the lack of details and context makes trying to reproduce this issue really hard, I suspect the problem here is due to the fact NetworkStreams (used, under the covers, by your MultipartReader instance) do not yet fully support CancellationTokens. In fact, almost every Socket-related operation on .NET Core just checks for the eventually passed CancellationToken upfront - which is useless, in my opinion.

The good news is that the .NET Core team is actively working on this and I believe the issue will be completely solved in .NET Core 3.0:

https://github.com/dotnet/corefx/issues/24430

As a temporary ugly workaround, you can change your code to wait for both a fabricated delay task and your call to ReadNextSectionAsync(), assuming you don't want to re-used that stalled socket / NetworkStream after that:

var timeoutTask = Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
var readNextSectionTask = multipartReader.ReadNextSectionAsync().ConfigureAwait(false);

if (await Task.WhenAny(timeoutTask, readNextSectionTask).ConfigureAwait(false) == timeoutTask)
{
    // TODO: Handle the timeout
}
else
{
    section = await readNextSectionTask;
}

Additionally, the fact you are not configuring your awaitable may act as a possible deadlock source (it is unclear to me whether you are running this code on ASP.NET Core itself or on some other synchronization context provider). To exclude this possibility, I would suggest to call ConfigureAwait(false) right after your await calls, as you can see on my previous code block.

Related