Warum funktioniert das Abbrechen von Aufgaben nicht und die Meldung ABGEBROCHEN wird nie angezeigt?
Hier ist mein Code:
Code: Select all
private const int DebounceDelayMs = 1000;
private CancellationTokenSource? cancellationSource;
[RelayCommand] private async Task OnTextChanged()
{
if (cancellationSource != null)
{
cancellationSource.Cancel();
Debug.WriteLine("CANCEL REQUESTED");
}
cancellationSource = new();
await DebounceGenerateQrCodeAsync(Code, cancellationSource.Token);
}
private async Task DebounceGenerateQrCodeAsync(string? text, CancellationToken cancellationToken)
{
try
{
Debug.WriteLine("UPDATE REQUESTED");
await Task.Delay(DebounceDelayMs, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
await GenerateQrCodeAsync(text, cancellationToken);
}
catch (OperationCanceledException)
{
Debug.WriteLine("CANCELED");
}
catch (Exception ex)
{
// Handle errors
}
}
private async Task GenerateQrCodeAsync(string? code, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(code))
{
QrCodePreview = null;
OnPropertyChanged(nameof(QrCodePreview));
return;
}
byte[] pixels = await Task.Run(() =>
{
// Generate QR code on background thread
using var qrGenerator = new QRCodeGenerator();
using var qrCodeData = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
using var qrCode = new PngByteQRCode(qrCodeData);
return qrCode.GetGraphic(20);
}, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
// some logic for main thread
using var stream = new MemoryStream(pixels);
using var randomAccessStream = stream.AsRandomAccessStream();
randomAccessStream.Seek(0);
cancellationToken.ThrowIfCancellationRequested();
var writeableBitmap = new WriteableBitmap(QrCodeWidth, QrCodeHeight);
await writeableBitmap.SetSourceAsync(randomAccessStream);
writeableBitmap.Invalidate();
cancellationToken.ThrowIfCancellationRequested();
Debug.WriteLine("UPDATE");
QrCodePreview = writeableBitmap;
OnPropertyChanged(nameof(QrCodePreview));
}
Mobile version