-
Notifications
You must be signed in to change notification settings - Fork 159
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
⚡ refactor(Sortable): add a detection mechanism for potential frequen…
…t rendering
- Loading branch information
Showing
3 changed files
with
58 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
namespace Masa.Blazor.Utils; | ||
|
||
/// <summary> | ||
/// The RenderRateLimiter class is used to limit the frequency of render operations. | ||
/// It throws an InvalidOperationException if the render count exceeds the specified threshold within one second. | ||
/// </summary> | ||
public class RenderRateLimiter | ||
{ | ||
private int _renderCount; | ||
private long _renderStartTimestamp; | ||
private readonly string _errorMessage; | ||
private readonly int _threshold; | ||
|
||
/// <summary> | ||
/// Initializes a new instance of the RenderRateLimiter class. | ||
/// </summary> | ||
/// <param name="errorMessage">The error message to be thrown when the render count exceeds the threshold.</param> | ||
/// <param name="threshold">The maximum number of renders allowed within one second. Default is 20.</param> | ||
public RenderRateLimiter(string errorMessage, int threshold = 20) | ||
{ | ||
_errorMessage = errorMessage; | ||
_threshold = threshold; | ||
} | ||
|
||
/// <summary> | ||
/// Records a render operation. If the render count exceeds the threshold within one second, an InvalidOperationException is thrown. | ||
/// </summary> | ||
public void RecordRender() | ||
{ | ||
if (_renderCount == 0) | ||
{ | ||
_renderStartTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds(); | ||
_renderCount++; | ||
} | ||
else | ||
{ | ||
_renderCount++; | ||
var now = DateTimeOffset.Now.ToUnixTimeSeconds(); | ||
if (now - _renderStartTimestamp > 1) | ||
{ | ||
var copy = _renderCount; | ||
_renderCount = 0; | ||
|
||
if (copy > _threshold) | ||
{ | ||
throw new InvalidOperationException(_errorMessage); | ||
} | ||
} | ||
} | ||
} | ||
} |