我正在为关闭时窗口窗体抛出的ObjectDisposedException而苦苦挣扎。在我的客户端-服务器应用程序中,在客户端捕获屏幕截图,然后通过TCP/IP发送到服务器,在那里更新表单。关闭此窗体时会出现问题。
下面是服务器端的代码:
// 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(ScreenShot 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;
}有人能告诉我我哪里做错了吗?
发布于 2011-03-23 05:43:06
来自MSDN:“您必须在映像的生命周期内保持流的打开状态。”
您可能有一个争用条件,根据该条件,在处置Image对象之前会先处置来自屏幕截图的MemoryStream。这很可能会导致异常。我不知道处理Image是否会处理底层流,但如果是这样,那就是另一个可能的问题。
发布于 2011-03-23 05:43:25
覆盖表单的OnClosing方法,并将侦听器对象(由appendToMemoryStream使用)设置为null。
最有可能发生的情况是,当窗体关闭时,您仍在传输屏幕。
使用BackgroundWorker然后取消它可能会更好。
https://stackoverflow.com/questions/5398061
复制相似问题