保存类在处置磁盘:我的代码是否有错误? [英] Saving a Class to disk on dispose: Does my code have bugs?

查看:84
本文介绍了保存类在处置磁盘:我的代码是否有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个简单的类,它本身序列化到磁盘时不再使用。我现在的代码(见下文)。我现在的代码似乎工作,但我不是在我的知识完全有信心,所以我想知道有没有人看,此代码的任何显著的问题。

 无效IDisposable.Dispose()
{
的Dispose(真);
GC.SuppressFinalize(本);
}

〜MyClass的()
{
的Dispose(假);
}

受保护的虚拟无效的Dispose(BOOL处置)
{
如果(!this.disposed)
{
的MemoryStream毫秒​​=新的MemoryStream();
BinaryFormatter的BF =新的BinaryFormatter();
bf.Serialize(MS,这一点);
字节[] =输出Dostuff(毫秒);
File.WriteAllBytes(DBPATH,输出);
}
this.disposed = TRUE;
}


解决方案

这几乎是不可能写一个终结正确,并且做这样一个工作仅仅是一个灾难。更何况,它会杀死的性能和无法调试。为终结规则1,永远不要使用它们。第2条(仅适用于高级用户)是,除非你真的确定你有没有使用这些。



如果它只是一个有趣的业余爱好项目那么就没有真正的伤害,它可能会工作不够好,但如果我见过在生产代码库这样的事情我哭了。



如果你想做些什么样这一点,那么我会做它一个明确的呼叫,只需使用终结调试,其中明确方法不叫,期间如

 <$赶上案件C $ C> MyClass类
{
私人布尔脏; //设置此每当对象改变

〜如果MyClass的
{
(this.dirty)
{
Debug.Fail(对象不拯救)。
}
}

公共无效保存()
{
如果(this.dirty)
{
// TODO :做节省
this.dirty = FALSE;
}
}
}


I am attempting to make a simple class that serializes itself to disk when it is no longer in use. The code I have right now (see below). The code I have now seems to work, but I am not fully confident in my knowledge, so I am wondering if anyone else sees any significant problems with this code.

void IDisposable.Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

~MyClass()
{
    Dispose(false);
}

protected virtual void Dispose(bool disposing)
{
    if (!this.disposed)
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms, this);
        byte[] output = Dostuff(ms);
        File.WriteAllBytes(DBPATH, output);
    }
    this.disposed = true;
}

解决方案

It is virtually impossible to write a finalizer correctly, and doing this sort of work in one is just a recipe for disaster. Not to mention it'll kill performance and be impossible to debug. Rule 1 for finalizers is don't ever use them. Rule 2 (for advanced users only) is don't use them unless you're really sure you have to.

If it's just for a fun hobby project then there's no real harm and it will probably work well enough, but I'd cry if I ever saw something like this in a production codebase.

If you do want to do something like this, then I'd make it an explicit call and simply use the finalizer to catch cases during debugging where the explicit method was not called, e.g.

class MyClass
{
    private bool dirty; // set this whenever the object changes

    ~MyClass 
    {
        if (this.dirty) 
        {
            Debug.Fail("Object was not saved.");
        }
    }

    public void Save()
    {
        if (this.dirty)
        {
            // TODO: do the save
            this.dirty = false;
        }
    }
}

这篇关于保存类在处置磁盘:我的代码是否有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆