开发者

ObjectDisposedException thrown by form

I'm struggling with an ObjectDisposedException thrown sometimes by a window form on closing. In my client - server application , at the client a screenshot is captured and then sended at the server through TCP/IP where it updates a form. The problem appears when this form is closed .

Here's the code at server :

 // here the bytes of the screenshot are received

 public void appendToMemoryStream(byte[] data, int offset)
        {
            if (!ms.CanWrite) return;    
            try
            {          
                ms.Write(data, offset, getCountForWrite(offset));
                lock (this)
                {
                    nrReceivedBytes = nrReceivedBytes + getCountForWrite(offset);
                    nrBytesToReceive = screenShotSize - nrReceivedBytes;
                }

                if (isScreenShotCompleted() && listener != null)
                {
                    listener.onReceiveScreenShotComplete(this);
                }
            }
            catch (Exception e)
            {
               MessageBox.Show("Error while receiving screenshot" + "\n" + e.GetType() + "\n" + e.StackTrace);
            }
        }




// the code that handles the receiving of a screenshot
public void onReceiveScreenShotComplete(S开发者_如何学CcreenShot scr)
        {

            this.screenshot = null;

            if (screen != null && screen.Visible)
            {
                screen.updateScreen(scr);
            }          
        }


// and the form
    public partial class Screen : Form
    {
        public string screenUniqueIdentifier;

        public Screen()
        {
            InitializeComponent();          
        }

        public void updateScreen(ScreenShot screenshot)
        {
           Image image = Image.FromStream(screenshot.getMemoryStream());
           this.Show();
           textBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
           textBox1.Image = image;        
        }

Can someone please point me where am I doing something wrong ?


From MSDN: "You must keep the stream open for the lifetime of the Image."

You may have a race condition by which the MemoryStream from the screenshot is being disposed prior to the Image object's disposal. This would likely cause the exception. I do not know whether disposing of the Image disposes of the underlying stream, but if it does, that is another possible issue.


Override the OnClosing method of the Form and set the listener object (used by appendToMemoryStream) to null.

What is most likely happening is that you are still transferring the screen when the form is being closed.

It might be better to use a BackgroundWorker and then cancel it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜