Исходный код вики Dispose

Версия 1.5 от Alexandr Fokin на 2023/02/15 23:27

Скрыть последних авторов
Alexandr Fokin 1.1 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]]
Alexandr Fokin 1.2 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}}
Alexandr Fokin 1.5 36 |(% style="width:465px" %)Отчистка управляемых ресурсов
37 (Соответственно не использует финализацию).|(% style="width:1030px" %){{code language="C#"}}public sealed class Foo : IDisposable
Alexandr Fokin 1.2 38 {
39 private readonly IDisposable _disposable1;
40 private readonly IDisposable _disposable2;
41
42 public Foo()
43 {
Alexandr Fokin 1.3 44 _disposable1 = new Bar();
45 _disposable2 = new Bar();
Alexandr Fokin 1.2 46 }
47
48 public void Dispose()
Alexandr Fokin 1.4 49 {
50 _disposable1.Dispose();
51 _disposable2.Dispose();
52 }
Alexandr Fokin 1.2 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}}