Исходный код вики Dispose
Редактировал(а) Alexandr Fokin 2024/06/02 16:03
Последние авторы
author | version | line-number | content |
---|---|---|---|
1 | Реализация метода Dispose | ||
2 | [[https:~~/~~/learn.microsoft.com/ru-ru/dotnet/standard/garbage-collection/implementing-dispose>>https://learn.microsoft.com/ru-ru/dotnet/standard/garbage-collection/implementing-dispose]] | ||
3 | |||
4 | ---- | ||
5 | |||
6 | |(% style="width:465px" %)Отчистка неуправляемых и управляемых ресурсов|(% style="width:1030px" %){{code language="C#"}}class BaseClassWithFinalizer : IDisposable | ||
7 | { | ||
8 | // To detect redundant calls | ||
9 | private bool _disposedValue; | ||
10 | |||
11 | ~BaseClassWithFinalizer() => Dispose(false); | ||
12 | |||
13 | // Public implementation of Dispose pattern callable by consumers. | ||
14 | public void Dispose() | ||
15 | { | ||
16 | Dispose(true); | ||
17 | GC.SuppressFinalize(this); | ||
18 | } | ||
19 | |||
20 | // Protected implementation of Dispose pattern. | ||
21 | protected virtual void Dispose(bool disposing) | ||
22 | { | ||
23 | if (!_disposedValue) | ||
24 | { | ||
25 | if (disposing) | ||
26 | { | ||
27 | // TODO: dispose managed state (managed objects) | ||
28 | } | ||
29 | |||
30 | // TODO: free unmanaged resources (unmanaged objects) and override finalizer | ||
31 | // TODO: set large fields to null | ||
32 | _disposedValue = true; | ||
33 | } | ||
34 | } | ||
35 | }{{/code}} | ||
36 | |(% style="width:465px" %)Отчистка управляемых ресурсов | ||
37 | (Соответственно не использует финализацию).|(% style="width:1030px" %){{code language="C#"}}public sealed class Foo : IDisposable | ||
38 | { | ||
39 | private readonly IDisposable _disposable1; | ||
40 | private readonly IDisposable _disposable2; | ||
41 | |||
42 | public Foo() | ||
43 | { | ||
44 | _disposable1 = new Bar(); | ||
45 | _disposable2 = new Bar(); | ||
46 | } | ||
47 | |||
48 | public void Dispose() | ||
49 | { | ||
50 | _disposable1.Dispose(); | ||
51 | _disposable2.Dispose(); | ||
52 | } | ||
53 | }{{/code}} | ||
54 | |(% style="width:465px" %)Наследование. Отчистка неуправляемых и управляемых ресурсов.|(% style="width:1030px" %){{code language="C#"}}class DerivedClassWithFinalizer : BaseClassWithFinalizer | ||
55 | { | ||
56 | // To detect redundant calls | ||
57 | private bool _disposedValue; | ||
58 | |||
59 | ~DerivedClassWithFinalizer() => this.Dispose(false); | ||
60 | |||
61 | // Protected implementation of Dispose pattern. | ||
62 | protected override void Dispose(bool disposing) | ||
63 | { | ||
64 | if (!_disposedValue) | ||
65 | { | ||
66 | if (disposing) | ||
67 | { | ||
68 | // TODO: dispose managed state (managed objects). | ||
69 | } | ||
70 | |||
71 | // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. | ||
72 | // TODO: set large fields to null. | ||
73 | _disposedValue = true; | ||
74 | } | ||
75 | |||
76 | // Call the base class implementation. | ||
77 | base.Dispose(disposing); | ||
78 | } | ||
79 | }{{/code}} | ||
80 | |(% style="width:465px" %)Пример использование механизма отчистки для воскрешения (resurrection) объекта. | ||
81 | \\Можно доработать для использования Dispose (не подавляется финализация, не выполняется повторная регистрация). | ||
82 | Если объект внутри себя использует другие финализируемые объекты, то внутри блока финализатора их состояние может быть недетерминировано (скорее всего их придется пересоздавать).|(% style="width:1030px" %){{code language="C#"}}class A { | ||
83 | private IObjectPool _pool = ...; | ||
84 | |||
85 | ~A() { | ||
86 | //will not die. keep a reference in resurectedA. | ||
87 | _pool.ReturnToPool(this); | ||
88 | GC.ReRegisterForFinalize(this); | ||
89 | } | ||
90 | }{{/code}} | ||
91 | |(% style="width:465px" %)Dispose struct и упаковка (boxing)|(% style="width:1030px" %)((( | ||
92 | If my struct implements IDisposable will it be boxed when used in a using statement? | ||
93 | [[https:~~/~~/stackoverflow.com/questions/2412981/if-my-struct-implements-idisposable-will-it-be-boxed-when-used-in-a-using-statem/2413844#2413844>>https://stackoverflow.com/questions/2412981/if-my-struct-implements-idisposable-will-it-be-boxed-when-used-in-a-using-statem/2413844#2413844]] | ||
94 | |||
95 | When does a using-statement box its argument, when it's a struct? | ||
96 | [[https:~~/~~/stackoverflow.com/questions/1330571/when-does-a-using-statement-box-its-argument-when-its-a-struct>>https://stackoverflow.com/questions/1330571/when-does-a-using-statement-box-its-argument-when-its-a-struct]] | ||
97 | ))) |