Skip to content

Commit

Permalink
use semaphore instead of lock
Browse files Browse the repository at this point in the history
  • Loading branch information
Edward Miller committed Apr 27, 2024
1 parent 48d5ebf commit 3a05266
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 11 deletions.
20 changes: 15 additions & 5 deletions src/Controls/src/Core/ImageSource.cs
Expand Up @@ -11,7 +11,7 @@ namespace Microsoft.Maui.Controls
[System.ComponentModel.TypeConverter(typeof(ImageSourceConverter))]
public abstract partial class ImageSource : Element
{
readonly object _synchandle = new object();
private readonly SemaphoreSlim _cancellationTokenSourceLock = new(1, 1);
CancellationTokenSource _cancellationTokenSource;

TaskCompletionSource<bool> _completionSource;
Expand Down Expand Up @@ -118,7 +118,7 @@ public static ImageSource FromUri(Uri uri)
return FromUri(uri);
}

private protected void OnLoadingCompleted(bool cancelled)
private protected async Task OnLoadingCompleted(bool cancelled)
{
if (!IsLoading || _completionSource == null)
return;
Expand All @@ -127,18 +127,28 @@ private protected void OnLoadingCompleted(bool cancelled)
if (tcs != null)
tcs.SetResult(cancelled);

lock (_synchandle)
await _cancellationTokenSourceLock.WaitAsync();
try
{
CancellationTokenSource = null;
}
finally
{
_cancellationTokenSourceLock.Release();
}
}

private protected void OnLoadingStarted()
private protected async Task OnLoadingStarted()
{
lock (_synchandle)
await _cancellationTokenSourceLock.WaitAsync();
try
{
CancellationTokenSource = new CancellationTokenSource();
}
finally
{
_cancellationTokenSourceLock.Release();
}
}

protected void OnSourceChanged()
Expand Down
6 changes: 3 additions & 3 deletions src/Controls/src/Core/StreamImageSource.cs
Expand Up @@ -35,17 +35,17 @@ async Task<Stream> IStreamImageSource.GetStreamAsync(CancellationToken userToken
if (IsEmpty)
return null;

OnLoadingStarted();
await OnLoadingStarted();
userToken.Register(CancellationTokenSource.Cancel);
Stream stream = null;
try
{
stream = await Stream(CancellationTokenSource.Token);
OnLoadingCompleted(false);
await OnLoadingCompleted(false);
}
catch (OperationCanceledException)
{
OnLoadingCompleted(true);
await OnLoadingCompleted(true);
throw;
}
return stream;
Expand Down
6 changes: 3 additions & 3 deletions src/Controls/src/Core/UriImageSource.cs
Expand Up @@ -56,18 +56,18 @@ async Task<Stream> IStreamImageSource.GetStreamAsync(CancellationToken userToken
if (IsEmpty)
return null;

OnLoadingStarted();
await OnLoadingStarted();
userToken.Register(CancellationTokenSource.Cancel);
Stream stream;

try
{
stream = await GetStreamAsync(Uri, CancellationTokenSource.Token);
OnLoadingCompleted(false);
await OnLoadingCompleted(false);
}
catch (OperationCanceledException)
{
OnLoadingCompleted(true);
await OnLoadingCompleted(true);
throw;
}
catch (Exception ex)
Expand Down

0 comments on commit 3a05266

Please sign in to comment.