1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Threading ;
4
+ using GenericMemoryCache ;
5
+ using Microsoft . Extensions . Caching . Memory ;
6
+
7
+ namespace Sample
8
+ {
9
+ class Program
10
+ {
11
+ static void Main ( string [ ] args )
12
+ {
13
+ // non-generic MemoryCache instance
14
+ IMemoryCache nonGeneric = new MemoryCache ( new MemoryCacheOptions ( ) ) ;
15
+
16
+ // GenericMemoryCache
17
+ IMemoryCache < int , Book > booksCache = nonGeneric . ToGeneric < int , Book > ( ) ;
18
+
19
+ Book CreateValue ( ICacheEntry < int , Book > entry )
20
+ {
21
+ entry . SetAbsoluteExpiration ( TimeSpan . FromSeconds ( 2 ) ) ;
22
+ Console . WriteLine ( $ "id = { entry . Key } created") ;
23
+ return entry . Value ;
24
+ }
25
+
26
+ // GetOrCreate
27
+ Book asp1 = booksCache . GetOrCreate ( 1 , CreateValue ) ;
28
+ // id = 1 created
29
+
30
+ Book scala1 = booksCache . GetOrCreate ( 2 , CreateValue ) ;
31
+ // id = 2 created
32
+
33
+ // cached
34
+ Book asp2 = booksCache . GetOrCreate ( 1 , CreateValue ) ;
35
+ Console . WriteLine ( $ "asp1 == asp2(cached): { asp1 == asp2 } ") ; // true
36
+
37
+ // Remove
38
+ booksCache . Remove ( 2 ) ;
39
+
40
+ // Create
41
+ Book scala2 = booksCache . GetOrCreate ( 2 , CreateValue ) ;
42
+ Console . WriteLine ( $ "scala1 == scala2(created): { scala1 == scala2 } ") ; // false
43
+
44
+ // Expire
45
+ Thread . Sleep ( TimeSpan . FromSeconds ( 5 ) ) ;
46
+
47
+ // Create
48
+ Book scala3 = booksCache . GetOrCreate ( 2 , CreateValue ) ;
49
+ // id = 2 created
50
+
51
+ Console . WriteLine ( "end." ) ;
52
+ Console . ReadLine ( ) ;
53
+ }
54
+ }
55
+
56
+ // てきとうなデータベースのかわり
57
+ public static class Database
58
+ {
59
+ private static Dictionary < int , Book > BooksDic = new Dictionary < int , Book > ( )
60
+ {
61
+ {
62
+ 1 , new Book ( )
63
+ {
64
+ Id = 1 ,
65
+ Title = "Programming ASP.NET" ,
66
+ Stock = 5
67
+ }
68
+ } ,
69
+ {
70
+ 2 , new Book ( )
71
+ {
72
+ Id = 2 ,
73
+ Title = "Programming in Scala" ,
74
+ Stock = 10
75
+ }
76
+ }
77
+ } ;
78
+
79
+ public static Book SelectBook ( int id ) => BooksDic . TryGetValue ( id , out Book book ) ? book . DeepCopy ( ) : null ;
80
+ }
81
+
82
+ public class Book
83
+ {
84
+ public int Id { get ; set ; }
85
+ public string Title { get ; set ; }
86
+ public int Stock { get ; set ; }
87
+
88
+ public Book DeepCopy ( )
89
+ => new Book ( )
90
+ {
91
+ Id = this . Id ,
92
+ Title = this . Title ,
93
+ Stock = this . Stock
94
+ } ;
95
+ }
96
+ }
0 commit comments