c# 为 multipartReader.ReadNextSectionAsync() 设置超时

c# set timeout for multipartReader.ReadNextSectionAsync()

提问人:Reza Akraminejad 提问时间:10/23/2018 最后编辑:Reza Akraminejad 更新时间:11/2/2018 访问量:1531

问:

我正在使用 C# .net core 从发送多个文件的多部分帖子用户读取上传数据。 如何防止在读取最后一个文件后无限次使用等待

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

虽然我已经将 cancelationToken 设置为 1 秒,但它是无限的,并且不会去 下一行,如果我将发送另一个请求。

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 是这个项目的内联类,这是 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;
        }
    }
C# async-await settimeout 多部分

评论

1赞 Nkosi 10/27/2018
上面的代码是怎么叫的?您还未包含封装方法签名。所描述的症状听起来像是死锁,因此建议先检查死锁。
0赞 Reza Akraminejad 10/27/2018
@Nkosi,我从流中读取数据,直到我到达\r\n\r\n,它读取所有标头,并从从中导出的字符串中,提取边界,并传递流和边界以读取部分。当想阅读最后一节但没有部分时有什么问题

答:

0赞 Efran Cobisi 11/2/2018 #1

虽然缺乏细节和上下文使得尝试重现这个问题变得非常困难,但我怀疑这里的问题是由于 NetworkStreams(在幕后由您的 MultipartReader 实例使用)尚未完全支持 CancellationTokens。事实上,.NET Core 上几乎每个与套接字相关的操作都只是预先检查最终传递的 CancellationToken - 在我看来,这是无用的。

好消息是,.NET Core 团队正在积极解决这个问题,我相信这个问题将在 .NET Core 3.0 中得到完全解决:

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

作为一种临时的丑陋解决方法,您可以更改代码以等待捏造的延迟任务和对 ReadNextSectionAsync() 的调用,假设您不想在此之后重复使用该停滞的套接字/NetworkStream:

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;
}

此外,您没有配置 awaitable 这一事实可能会充当可能的死锁源(我不清楚您是在 ASP.NET Core 本身还是在其他一些同步上下文提供程序上运行此代码)。为了排除这种可能性,我建议在 await 调用后立即调用 ConfigureAwait(false),正如您在我之前的代码块中看到的那样。

评论

0赞 Reza Akraminejad 11/5/2018
@erfancobisi 我已经通过 mono 旧源代码中的组件解决了这个问题:mono-project.com jgauffin/Griffin.WebServer