-
Notifications
You must be signed in to change notification settings - Fork 560
/
MemoryManager.cs
79 lines (67 loc) · 2.1 KB
/
MemoryManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Runtime;
using Serilog;
namespace Abot2.Util
{
/// <summary>
/// Handles memory monitoring/usage
/// </summary>
public interface IMemoryManager : IMemoryMonitor, IDisposable
{
/// <summary>
/// Whether the current process that is hosting this instance is allocated/using above the param value of memory in mb
/// </summary>
bool IsCurrentUsageAbove(int sizeInMb);
/// <summary>
/// Whether there is at least the param value of available memory in mb
/// </summary>
bool IsSpaceAvailable(int sizeInMb);
}
public class MemoryManager : IMemoryManager
{
IMemoryMonitor _memoryMonitor;
public MemoryManager(IMemoryMonitor memoryMonitor)
{
if (memoryMonitor == null)
throw new ArgumentNullException("memoryMonitor");
_memoryMonitor = memoryMonitor;
}
public virtual bool IsCurrentUsageAbove(int sizeInMb)
{
return GetCurrentUsageInMb() > sizeInMb;
}
public virtual bool IsSpaceAvailable(int sizeInMb)
{
if (sizeInMb < 1)
return true;
var isAvailable = true;
MemoryFailPoint _memoryFailPoint = null;
try
{
_memoryFailPoint = new MemoryFailPoint(sizeInMb);
}
catch (InsufficientMemoryException)
{
isAvailable = false;
}
catch (NotImplementedException)
{
Log.Warning("MemoryFailPoint is not implemented on this platform. The MemoryManager.IsSpaceAvailable() will just return true.");
}
finally
{
if (_memoryFailPoint != null)
_memoryFailPoint.Dispose();
}
return isAvailable;
}
public virtual int GetCurrentUsageInMb()
{
return _memoryMonitor.GetCurrentUsageInMb();
}
public void Dispose()
{
_memoryMonitor.Dispose();
}
}
}