开发者

Access disposed DataContext from linq to SQL

I have a linq2sql datacontext which gets disposed. But when I check for null, I always have a false condition.

DataClasses1DataContext dc = new DataClasses1DataContext();
dc.Dispose();

some other code further

if (dc == null) {
    // ALWAYS 开发者_StackOverflow社区FALSE
}

How can i find out if the datacontext has been disposed?

UPDATE: Let me clarify myself. I get a datacontext but sometimes the external code passes an object (which is not null, but is already disposed). I need to check if the object exists. I was thinking of something else than a try-catch.


The DataContext class doesn't expose any properties that can tell you whether it's been disposed.
However, you can make one yourself by overriding the Dispose(bool) method:

public bool IsDisposed { get; private set; }
protected override void Dispose(bool disposing) {
    IsDisposed = true;
}


Calling Dispose() doesn't clear the references to the object. If dc is a field, then a simple way to handle this that works for all diaposable classes would be to manually assign dc = null; immediately after you call Dispose(). This also means that the data-context can be eligible for garbage-collection even if your class lives for much longer.

If dc is a local variable, just use:

using(var dc = new YourDataContext()) {
    ...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜