diff --git a/src/Controls/src/Core/ImageSource.cs b/src/Controls/src/Core/ImageSource.cs index ce922a809593..63bf8dd978d9 100644 --- a/src/Controls/src/Core/ImageSource.cs +++ b/src/Controls/src/Core/ImageSource.cs @@ -52,16 +52,14 @@ public virtual Task Cancel() if (!IsLoading) return Task.FromResult(false); - var tcs = new TaskCompletionSource(); - TaskCompletionSource original = Interlocked.CompareExchange(ref _completionSource, tcs, null); - if (original == null) + TaskCompletionSource original = Interlocked.CompareExchange(ref _completionSource, new TaskCompletionSource(), null); + if (original is null) { _cancellationTokenSource.Cancel(); + return Task.FromResult(false); } - else - tcs = original; - return tcs.Task; + return original.Task; } /// diff --git a/src/Controls/tests/Core.UnitTests/ImageSourceTests.cs b/src/Controls/tests/Core.UnitTests/ImageSourceTests.cs index b9b9e25781ad..690d72ab05f1 100644 --- a/src/Controls/tests/Core.UnitTests/ImageSourceTests.cs +++ b/src/Controls/tests/Core.UnitTests/ImageSourceTests.cs @@ -156,5 +156,16 @@ public void ImplicitCastOnAbsolutePathsShouldCreateAFileImageSource() var image = new Image { Source = path }; Assert.IsType(image.Source); } + + [Fact] + public async Task CancelCompletes() + { + var imageSource = new StreamImageSource + { + Stream = _ => Task.FromResult(new MemoryStream()) + }; + await ((IStreamImageSource)imageSource).GetStreamAsync(); + await imageSource.Cancel(); // This should complete! + } } }