Skip to content

Commit

Permalink
Use CancelationToken to end thread with cursor
Browse files Browse the repository at this point in the history
  • Loading branch information
KarmaKamikaze committed Nov 7, 2023
1 parent c3d18b3 commit 33bab15
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
22 changes: 14 additions & 8 deletions ChatRPG/Pages/Index.razor
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
@page "/"

@implements IDisposable

<AuthorizeView>
<NotAuthorized>
Expand All @@ -24,16 +24,16 @@
private readonly string _fullTitleText = "ChatRPG";
private string _titleDisplayText = "";
private bool _cursorVisible = true;
private bool _isPageLoaded = true; // set to false when leaving page
private readonly CancellationTokenSource _cts = new CancellationTokenSource();

protected override async Task OnInitializedAsync()
{
// Start cursor blinking on a separate thread
await Task.Factory.StartNew(BlinkCursorAsync, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
await TypingAsync();
await Task.Factory.StartNew(() => BlinkCursorAsync(_cts.Token), _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
await TypingAnimateAsync();
}

private async Task TypingAsync()
private async Task TypingAnimateAsync()
{
for (int i = 0; i <= _fullTitleText.Length; i++)
{
Expand All @@ -43,14 +43,20 @@
}
}

private async Task BlinkCursorAsync()
private async Task BlinkCursorAsync(CancellationToken cancellationToken)
{
while (_isPageLoaded)
while (!cancellationToken.IsCancellationRequested)
{
_cursorVisible = !_cursorVisible; // Toggle cursor visibility
await Task.Delay(500); // Adjust the delay between blinks
await Task.Delay(500, cancellationToken); // Adjust the delay between blinks
await InvokeAsync(StateHasChanged);
}
}

public void Dispose()
{
_cts.Cancel(); // Request cancellation when the component is about to be removed
_cts.Dispose(); // Dispose of the CancellationTokenSource
}

}
7 changes: 0 additions & 7 deletions ChatRPG/wwwroot/css/site.css
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,6 @@ a, .btn-link {
animation: fadeIn 3s;
}

.typing {
overflow: hidden; /* Hide overflowing text */
border-right: .15em solid orange; /* Typing cursor */
white-space: nowrap; /* Keeps text on a single line */
margin: 0 auto; /* Center the text horizontally */
}

.cursor {
position: relative;
top: -0.1em; /* Adjust the value to raise or lower the cursor */
Expand Down

0 comments on commit 33bab15

Please sign in to comment.