如何通过HTTPWebRequest正确中止上传?

时间:2013-05-22 06:33:36

标签: c# multithreading httpwebrequest

ImageFile currImage = (ImageFile)image;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(BuildUrl(currImage.Meta));
req.AllowWriteStreamBuffering = false;
req.Method = "POST";                                
req.ContentType = currImage.MimeType;
req.ContentLength = currImage.Meta.Length;

var fileStream = new FileStream(
                    currImage.Meta.FullName,
                    FileMode.Open,
                    FileAccess.Read, // Allows share file with other processes !important
                    FileShare.Read
                );

// Prepare to read the file and push it into request stream
using (BinaryReader fileReader = new BinaryReader(fileStream))
{
    using (Stream requestStream = req.GetRequestStream())
    {
        // Create a buffer for image data
        const int bufSize = 1024;
        byte[] buffer = new byte[bufSize];
        int chunkLength = 0;

        // Transfer data
        while ((chunkLength = fileReader.Read(buffer, 0, bufSize)) > 0)
        {
            IAsyncResult result = requestStream.BeginWrite(buffer, 0, chunkLength, null, null);

            // Check for cancellation here <-----
            if (token.IsCancellationRequested)
            {                               
                _logger.Info(String.Format("Uploading {0} was cancelled in process.", currImage.Meta.FullName));                                
                token.ThrowIfCancellationRequested();
            }

            result.AsyncWaitHandle.WaitOne();
            requestStream.EndWrite(result);
        }
    }
}

try
{
    // Read image ID from the response
    WebResponse response = req.GetResponse();
    TextReader responseReader = new StreamReader(response.GetResponseStream());

    string imageId = responseReader.ReadToEnd();

    long id;
    if (String.IsNullOrEmpty(imageId) && !Int64.TryParse(imageId, out id))
        throw new Exception("Wrong response for an uploaded image");
}
catch (Exception exp)
{
    _logger.Error(String.Format("Unable to read ImageId answer: {0}", exp.ToString()));                 
}

我正在使用此代码将文件上传到我的服务器,但如果有取消情况,如果在上传过程中出现取消,我会收到错误。

System.Net.WebException:请求已中止:请求已取消。 ---&GT; System.IO.IOException:在写入所有字节之前无法关闭流。    在System.Net.ConnectStream.CloseInternal(Boolean internalCall,Boolean aborting)    ---内部异常堆栈跟踪结束---    在System.Net.ConnectStream.CloseInternal(Boolean internalCall,Boolean aborting)    在System.Net.ConnectStream.System.Net.ICloseEx.CloseEx(CloseExState closeState)    在System.Net.ConnectStream.Dispose(布尔处理)    在System.IO.Stream.Close()    在System.IO.Stream.Dispose()

如何正确管理?我试图在token.ThrowIfCancellationRequested();

之前手动调用req.Abort()或requestStream.Close()

我理解为什么会出现这个错误,但我不知道怎么说系统没关系 - 我想打破连接。

0 个答案:

没有答案