none
postasync - System.ObjectDisposedException: Cannot access a disposed object. RRS feed

  • Question

  •  
    hi,

    I have an upload file function. I upload the file in chunks, it tries to upload a chunk, upon login failure tries to login again and then retries to upload. On some files it works fine and on some not (no consistencies as to which files fail and which upload - same file one time works another not).

    the error i get:

    in upload file function: System.ObjectDisposedException: Cannot access a disposed object.
    Object name: 'System.Net.Http.MultipartFormDataContent'.
       at System.Net.Http.HttpContent.CheckDisposed()
       at System.Net.Http.HttpContent.CopyToAsync(Stream stream, TransportContext context)
       at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at

    the function:

    private bool uploadFile(string path, ref string fileName)
            {

                var chunkSize = 1024 * 1024;
                var identifier = Guid.NewGuid();
                using (var fileStream = File.OpenRead(path))
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    var count = 1;
                    var totalChunkCount = Math.Ceiling((double)fileStream.Length / chunkSize);
                    HttpResponseMessage response = null;
                    while (fileStream.Position < fileStream.Length)
                    {
                        var readCount = fileStream.Length - fileStream.Position > chunkSize
                            ? chunkSize
                            : (int)(fileStream.Length - fileStream.Position);
                        var buffer = new byte[readCount];
                        fileStream.Read(buffer, 0, readCount);
                        using (var chunkedStream = new MemoryStream(buffer))
                        {
                            using (var content = new MultipartFormDataContent())
                            {
                                content.Add(new StreamContent(chunkedStream),
                                    Path.GetFileNameWithoutExtension(path), Path.GetFileName(path));
                                content.Add(new StringContent(count.ToString()), "ChunkNumber");
                                content.Add(new StringContent(totalChunkCount.ToString()), "TotalChunks");
                                content.Add(new StringContent(identifier), "Identifier");
                                content.Add(new StringContent(Path.GetFileName(path)), "Filename");

                                response = client.PostAsync(m_uploadURL, content).GetAwaiter().GetResult();
                                if (!response.IsSuccessStatusCode && response.StatusCode == HttpStatusCode.Unauthorized)
                                {
                                    login();
                                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                                    response = client.PostAsync(m_uploadURL, content).GetAwaiter().GetResult();
                                }
                            }
                        }
                        ShowPercentProgress("Upload of  " + path, count, Convert.ToInt32(totalChunkCount));
                        count++;
                    }

                    if (response != null)
                    {
                        var contents = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                        var json = JObject.Parse(contents);
                        var uploadResponse = json.ToObject<UploadResponse>();
                        if (!uploadResponse.status.isSuccess)
                        {
                            Logger.Log("Error: " + uploadResponse.status.statusDescription);
                            return false;
                        }
                        if (uploadResponse.data.allChunksUploaded)
                        {
                            serverFileName = uploadResponse.data.fileName;
                            return true;
                        }
                    }
                }

                return false;
            }

    Tuesday, March 24, 2020 12:23 PM

All replies

  • Hi MeTehila,
    >>  using (var client = new HttpClient())
    Although HttpClient implements IDisposable, it is best not to use it in a using block. So it is recommended to use a single instance of HttpClient throughout the life of the application. 

    private static HttpClient Client = new HttpClient();

    Here is a similar issue you can refer to.
    [Why is this HttpClient usage giving me an “Cannot access a disposed object.” error?]
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, March 25, 2020 2:51 AM
  • hi, thanks for the answer but i still get every once in a while:

     Error: in upload file ObjectDisposedException: System.ObjectDisposedException: Cannot access a disposed object.
    Object name: 'System.Net.Http.MultipartFormDataContent'.
       at System.Net.Http.HttpContent.CheckDisposed()
       at System.Net.Http.HttpContent.CopyToAsync(Stream stream, TransportContext context)
       at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

    Wednesday, March 25, 2020 11:53 AM
  • it is still sometimes  diposing the content :(
    Wednesday, March 25, 2020 12:24 PM
  • Hi MeTehila,
    This is a rare situation that I can't reproduce. So it is recommended to report a problem on the Developer Community and you can get more professional answer.
    Thank you for your understanding.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, March 27, 2020 8:57 AM