Warm tip: This article is reproduced from stackoverflow.com, please click
c# model-view-controller memorystream

C#

发布于 2020-03-28 23:16:36

As my code is shown below, the uploaded image file is sometimes read empty (fileContents is set to 0) or half read. As I have tested I could see that fileContents is receiving the proper value when I slowly step-over from myViewModel.File.CopyToAsync(memoryStream); to myViewModel.Image =... using the debug mode. So I believe there is a problem with the memorystream copy but I don't understand why.

However when I sleep the thread by removing the commented System.Threading.Thread.Sleep(1000); then reading the image is done propely and the fileContents get the proper value. Can the problem be caused by the declaration using (var memoryStream = new MemoryStream())? What is the problem caused by and is there a better way to fix this issue rather than sleeping the thread?

  if (myViewModel.File != null)
        {
            byte[] fileContents;
            using (var memoryStream = new MemoryStream())
            {
                myViewModel.File.CopyToAsync(memoryStream);
                //System.Threading.Thread.Sleep(1000);
                fileContents = memoryStream.ToArray();
                myViewModel.Image = new MyImage{ FileName = myViewModel.File.FileName, File = myViewModel.File, ContentType = myViewModel.File.ContentType, FileData = fileContents };
            }
        }
Questioner
DA_VDCT
Viewed
20
Devesh S 2020-01-31 17:53

You are not waiting for myViewModel.File.CopyToAsync(memoryStream) to complete.

Either use

await myViewModel.File.CopyToAsync(memoryStream);

or don't use async at all:

myViewModel.File.CopyTo(memoryStream);