通过HTTP上的WCF上传流式文件的IOException

时间:2013-05-06 11:12:55

标签: c# wcf c#-4.0 streaming

我正在构建托管的WCF服务,允许客户端通过HTTP上传文件。该服务按块读取客户端的Stream块。这适用于小文件,只需要一次迭代。但是,在一些块之后上传较大的文件时,我会在IOExceptionAn exception has been thrown when reading the stream.Stream.EndRead()

内部异常是The I/O operation has been aborted because of either a thread exit or an application request.

读取块的数量各不相同,但我无法弄清楚,导致差异的原因。它的工作时间从300毫秒到550毫秒不等,大约1MB到2MB处理。

有没有人有线索?

界面定义如下:

[ServiceContract]
  public interface IServiceFileserver
  {
    [OperationContract]
    UploadResponse UploadFile(UploadRequest uploadRequest);

    // All status feedback related code is left out for simplicity
    // [OperationContract]
    // RunningTaskStatus GetProgress(Guid taskId); 
  }

  [MessageContract]
  public class UploadRequest
  {
    [MessageHeader()]
    public string FileName { get; set; }

    [MessageHeader()]
    public long SizeInByte { get; set; }

    [MessageBodyMember(Order = 1)]
    public Stream Stream { get; set; }
  }

  [MessageContract]
  public class UploadResponse
  {
    [MessageBodyMember()]
    public Guid TaskId { get; set; }
  }

以下是服务实施:

const int bufferSize = 4 * 1024;
// This is called from the client side
public UploadResponse UploadFile(UploadRequest uploadRequest)
{
  Guid taskId = Guid.NewGuid();
  Stream stream = null;
  try
  {
    stream = uploadRequest.Stream;
    string filename = uploadRequest.FileName;
    long sizeInBytes = uploadRequest.SizeInByte;
    byte[] buffer = new byte[bufferSize];

    stream.BeginRead(buffer, 0, bufferSize, ReadAsyncCallback, new AsyncHelper(buffer, stream, sizeInBytes));
  }
  catch (Exception ex)
  {
    if (stream != null)
      stream.Close();
  }
  return new UploadResponse() { TaskId = taskId };
}

// Helper class for the async reading
public class AsyncHelper
{
  public Byte[] ByteArray { get; set; }
  public Stream SourceStream { get; set; }
  public long TotalSizeInBytes { get; set; }
  public long BytesRead { get; set; }

  public AsyncHelper(Byte[] array, Stream sourceStream, long totalSizeInBytes)
  {
    this.ByteArray = array;
    this.SourceStream = sourceStream;
    this.TotalSizeInBytes = totalSizeInBytes;
    this.BytesRead = 0;
  }
}

// Internal reading of a chunk from the stream
private void ReadAsyncCallback(IAsyncResult ar)
{
  AsyncHelper info = ar.AsyncState as AsyncHelper;
  int amountRead = 0;
  try
  {
    amountRead = info.SourceStream.EndRead(ar);
  }
  catch (IOException ex)
  {
    Trace.WriteLine(ex.Message);
    info.SourceStream.Close();
    return;
  }

  // Do something with the stream
  info.BytesRead += amountRead;
  Trace.WriteLine("info.BytesRead: " + info.BytesRead);

  if (info.SourceStream.Position < info.TotalSizeInBytes)
  {
    try
    { // Read next chunk from stream
      info.SourceStream.BeginRead(info.ByteArray, 0, info.ByteArray.Length, ReadAsyncCallback, info);
    }
    catch (IOException ex)
    {
      info.SourceStream.Close();
    }
  }
  else
  {
    info.SourceStream.Close();     
  }
}

绑定的定义如下:

BasicHttpBinding binding = new BasicHttpBinding();
binding.TransferMode = TransferMode.Streamed;
binding.MessageEncoding = WSMessageEncoding.Mtom;
binding.MaxReceivedMessageSize = 3 * 1024 * 1024;
binding.MaxBufferSize = 64 * 1024;
binding.CloseTimeout = new TimeSpan(0, 1, 0);
binding.OpenTimeout = new TimeSpan(0, 1, 0);
binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
binding.SendTimeout = new TimeSpan(0, 1, 0);
binding.Security.Mode = BasicHttpSecurityMode.None;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

1 个答案:

答案 0 :(得分:2)

uploadRequest.Stream是由WCF提供的Stream。此流可能会提供WCF与您的服务客户端维护的基础TCP连接。

此流与服务客户端传入的对象实例相同。这是不可能的,因为客户端和服务器仅通过TCP连接。它们不共享相同的地址空间,因此它们无法共享对象实例。

您在完成流处理之前从UploadFile返回。 WCF无法知道您的后台线程仍在使用此Stream对象。因此,WCF释放了流的基础资源(可能会关闭与客户端的TCP连接)。

一旦您的请求处理方法返回,WCF将关闭该流。然后,您的异步处理将无法确定地失败。这是你使用流和WCF赛车关闭它之间的线程竞赛。

问题下的评论显示某处存在误解,但我不确定它是什么。如果您需要进一步澄清,请发表评论,说出您不同意的内容以及原因。