-
-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: Refactor MailSender to use a queue
- Loading branch information
Showing
3 changed files
with
161 additions
and
35 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,54 @@ | ||
namespace GZCTF.Utils; | ||
|
||
public sealed class AsyncManualResetEvent | ||
{ | ||
private volatile TaskCompletionSource<bool> _tcs = new(); | ||
|
||
public async Task WaitAsync(CancellationToken cancellationToken = default) | ||
{ | ||
var tcs = _tcs; | ||
var cancelTcs = new TaskCompletionSource<bool>(); | ||
|
||
cancellationToken.Register( | ||
s => ((TaskCompletionSource<bool>)s!).TrySetCanceled(), cancelTcs); | ||
|
||
await await Task.WhenAny(tcs.Task, cancelTcs.Task); | ||
} | ||
|
||
private async Task<bool> Delay(int milliseconds) | ||
{ | ||
await Task.Delay(milliseconds); | ||
return false; | ||
} | ||
|
||
public async Task<bool> WaitAsync(int milliseconds, CancellationToken cancellationToken = default) | ||
{ | ||
var tcs = _tcs; | ||
var cancelTcs = new TaskCompletionSource<bool>(); | ||
|
||
cancellationToken.Register( | ||
s => ((TaskCompletionSource<bool>)s!).TrySetCanceled(), cancelTcs); | ||
|
||
return await await Task.WhenAny(tcs.Task, cancelTcs.Task, Delay(milliseconds)); | ||
} | ||
|
||
public void Set() | ||
{ | ||
var tcs = _tcs; | ||
Task.Factory.StartNew(s => ((TaskCompletionSource<bool>)s!).TrySetResult(true), | ||
tcs, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default); | ||
tcs.Task.Wait(); | ||
} | ||
|
||
public void Reset() | ||
{ | ||
var newTcs = new TaskCompletionSource<bool>(); | ||
while (true) | ||
{ | ||
var tcs = _tcs; | ||
if (!tcs.Task.IsCompleted || | ||
Interlocked.CompareExchange(ref _tcs, newTcs, tcs) == tcs) | ||
return; | ||
} | ||
} | ||
} |