1

我已经制作了一个 userControl 库 .. 它包含 NetworkStream、StreamReader、FileStream
所以当有这个 userControl 的表单关闭时,我是否必须将它们全部处理掉?

Form1_FormClosing(object sender,FormClosingEventArgs e)我的意思是 userControl 中没有这样的东西,所以我应该什么时候处理这​​些流?
userControl1.Dispose() 会解决这个问题吗?

提前致谢 :)

4

2 回答 2

4

UserControl.Dispose()处理它的Controls集合中的组件,但仅此而已。

您可以处理UserControl.Disposed事件,也可以正确实现 Dispose 模式

对于 C# 用户控件,protected override void Dispose(bool disposing)UserControl1.Designer.cs. 您可以将其修改为:

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        if (components != null)
        {
            components.Dispose();
        }

        // Dispose your streams here
    }

    base.Dispose(disposing);
}
于 2012-03-24T09:43:50.140 回答
0

userControl1.Dispose() does not magically take care of it unless you override it and put in code to dispose your objects, which is what you should do.

Have a look at this answer to see how to implement it, replace the event de-regestering with your calls to dispose your streams.

于 2012-03-24T09:38:27.917 回答