Why this code works

Dim PctStream As MemoryStream = Await GetSomePct() Me.BackgroundImage = Bitmap.FromStream(PctStream) 

but this one is not?

 Using PctStream As MemoryStream = Await GetSomePct() Me.BackgroundImage = Bitmap.FromStream(PctStream) End Using 

In the case of Using , a crossed-out rectangle is displayed instead of a picture.

    1 answer 1

    The problem is that you close stream , which GDI + refers to when drawing.

    On MSDN there is a note:

    You must keep the stream open during the lifetime of the Image.

    • Strangely, a similar construction with FileStream, but without await, I successfully work - 4per
    • @ 3per, i.e. using (FileStream fs = new FileStream ("picture path", FileMode.Open)) BackgroundImage = Bitmap.FromStream (fs); will work without Exception? Or on vb: Using fs As New FileStream ("path to picture", FileMode.Open) BackgroundImage = Bitmap.FromStream (fs) End Using - skubarenko
    • Yes, your code causes an exception, and the exception does not occur when the property value is set, it passes normally, but after, apparently, when the form is drawn. - 4per
    • @ 3per, and in what case did you work successfully? - skubarenko
    • PictureBox we throw on the form using (FileStream fs = new FileStream (@ "C: \ 2.jpg", FileMode.Open)) pictureBox1.Image = Bitmap.FromStream (fs); - 4per