Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CancellationToken Parameter to Methods Returning Task and ValueTask #1503

Merged
merged 55 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
9b77158
Update .editorconfig
brminnick Nov 7, 2023
00f814a
Merge branch 'main' into Add-CancellationToken-to-Async-Methods
brminnick Nov 7, 2023
aefa54e
Update DrawingViewService.windows.cs
brminnick Nov 7, 2023
1a1502b
Add `CancellationToken` to IDrawingView, IAlert, AnimationBehavior
brminnick Nov 7, 2023
d0f60b0
Update AvatarViewGesturesPage
brminnick Nov 7, 2023
61a8079
Update SpeechToTextImplementation.windows.cs
brminnick Nov 7, 2023
039b4dd
Merge branch 'Add-CancellationToken-to-Async-Methods' of https://gith…
brminnick Nov 7, 2023
fe0d0a1
Update SpeechToTextImplementation.windows.cs
brminnick Nov 7, 2023
ba133e4
Merge branch 'Add-CancellationToken-to-Async-Methods' of https://gith…
brminnick Nov 7, 2023
218f5df
Add CancellationToken
brminnick Nov 7, 2023
4131919
Update Unit Tests
brminnick Nov 7, 2023
166e972
Fix Failing Unit Tests
brminnick Nov 7, 2023
681b69e
Merge branch 'main' into Add-CancellationToken-to-Async-Methods
brminnick Nov 7, 2023
903613f
Merge branch 'main' into Add-CancellationToken-to-Async-Methods
brminnick Nov 7, 2023
b81d890
Merge branch 'main' into Add-CancellationToken-to-Async-Methods
brminnick Nov 7, 2023
eda0d93
Remove Duplicative `ThrowIfCancellationRequested()`
brminnick Nov 7, 2023
206a666
Remove Duplicate `ThrowIfCancellationRequested()`
brminnick Nov 7, 2023
378aa8e
Add Timeout to `async Task` Unit Tests
brminnick Nov 8, 2023
bcebba1
Fix Unit Test Timeouts
brminnick Nov 8, 2023
6d6a799
Update `AnimateCommand` (`ICommand` -> `Command<CancellationToken> `)
brminnick Nov 8, 2023
16ec80d
`dotnet format`
brminnick Nov 8, 2023
cd43208
Fix typo
brminnick Nov 8, 2023
e83e343
Fix compiler bug
brminnick Nov 8, 2023
349a30a
Update DrawingViewService.tizen.cs
brminnick Nov 8, 2023
6b6c732
Fix Unit Test Timeout
brminnick Nov 8, 2023
8358094
Fix BaseTest Inheritance
brminnick Nov 8, 2023
e80343f
Refactor using TaskCompletionSource
brminnick Nov 8, 2023
408a04d
Add CancellationToken
brminnick Nov 8, 2023
3eea517
Increase `TestDuration.Short`
brminnick Nov 8, 2023
55f0744
Increase to TestDuration.Long
brminnick Nov 8, 2023
2151fd6
Increase to TestDuration.Medium
brminnick Nov 8, 2023
43c9a97
Revert to `ICommand ForceValidateCommand`
brminnick Nov 8, 2023
bf6d5c2
Update ValidationBehavior.shared.cs
brminnick Nov 8, 2023
3518684
Update `void SeekTo(TimeSpan)` -> `Task SeekTo(TimeSpan, Cancellatio…
brminnick Nov 8, 2023
a31bc24
Implement `IDisposable` pattern
brminnick Nov 8, 2023
d7500c0
Update `PlatformSeek()`
brminnick Nov 8, 2023
8794e22
Promote PlatformSeek to `Task`
brminnick Nov 8, 2023
dde2da1
Fix Floating Point Comparison Bug
brminnick Nov 8, 2023
10334b2
Update Windows + Tizen MediaElement
brminnick Nov 8, 2023
a524f6d
Update MauiMediaElement.windows.cs
brminnick Nov 8, 2023
3683b83
Refactor + Optimize Code
brminnick Nov 8, 2023
f46a334
Add CancellationToken Unit Tests for `Alerts`, `Animations` and `Beha…
brminnick Nov 8, 2023
176f54b
Add CancellationToken Unit Tests for Converters
brminnick Nov 9, 2023
69e2ea6
Ad Unit Tests for Extensions
brminnick Nov 9, 2023
d41ea8f
Add Unit Tests for Layouts
brminnick Nov 9, 2023
4a56c9c
Add CancellationToken for PopupService
brminnick Nov 9, 2023
b8cc683
Add Views CancellationToken Unit Tests
brminnick Nov 9, 2023
f1bf0d5
Add Default Value to CancellationToken Parameter on Public APIs
brminnick Nov 9, 2023
a45a233
Update CONTRIBUTING.md
brminnick Nov 9, 2023
9490a1b
`dotnet format`
brminnick Nov 9, 2023
a7512c1
`dotnet format`
brminnick Nov 9, 2023
ece95a0
Merge branch 'main' into Add-CancellationToken-to-Async-Methods
brminnick Nov 9, 2023
84b6d68
Update src/CommunityToolkit.Maui/Behaviors/AnimationBehavior.shared.cs
brminnick Nov 9, 2023
80953f2
Update src/CommunityToolkit.Maui/Behaviors/AnimationBehavior.shared.cs
brminnick Nov 9, 2023
dc4390a
Merge branch 'main' into Add-CancellationToken-to-Async-Methods
brminnick Nov 9, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestions
csharp_style_conditional_delegate_call = true:suggestion

# Naming rules

Expand Down Expand Up @@ -122,6 +122,9 @@ dotnet_diagnostic.CA1050.severity = error
# CA2016: Forward the 'cancellationToken' parameter methods that take one
dotnet_diagnostic.CA2016.severity = error

# CA1068: CancellationToken parameters must come last
dotnet_diagnostic.CA1068.severity = error

# CA2208: Method passes parameter as the paramName argument to a ArgumentNullException constructor. Replace this argument with one of the method's parameter names. Note that the provided parameter name should have the exact casing as declared on the method.
dotnet_diagnostic.CA2208.severity = error

Expand Down
6 changes: 6 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,12 @@ Here we will have some:
### Debug Logging
* Always use `Trace.WriteLine()` instead of `Debug.WriteLine` for debug logging because `Debug.WriteLine` is removed by the compiler in Release builds

### Methods Returning Task and ValueTask
* Always include a `CancellationToken` as a parameter to every method returning `Task` or `ValueTask`
* If the method is public, provide a the default value for the `CancellationToken` (eg `CancellationToken token = default`)
* If the method is not publc, do not provide a default value for the `CancellationToken`
* Use `CancellationToken.ThrowIfCancellationRequested()` to verify the `CancellationToken`

### Enums
* Always use `Unknown` at index 0 for return types that may have a value that is not known
* Always use `Default` at index 0 for option types that can use the system default option
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,18 @@ async void DisplayCustomSnackbarButtonClicked(object? sender, EventArgs args)
options,
DisplayCustomSnackbarButton);

await customSnackbar.Show();
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await customSnackbar.Show(cts.Token);

DisplayCustomSnackbarButton.Text = dismissCustomSnackbarText;
}
else if (DisplayCustomSnackbarButton.Text is dismissCustomSnackbarText)
{
if (customSnackbar is not null)
{
await customSnackbar.Dismiss();
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await customSnackbar.Dismiss(cts.Token);

customSnackbar.Dispose();
}

Expand Down Expand Up @@ -102,7 +105,7 @@ await Application.Current.MainPage.Navigation.PushModalAsync(new ContentPage

Children =
{
new Button { Command = new AsyncRelayCommand(() => Snackbar.Make("Snackbar in a Modal Page").Show()) }
new Button { Command = new AsyncRelayCommand(token => Snackbar.Make("Snackbar in a Modal Page").Show(token)) }
.Top().CenterHorizontal()
.Text("Display Snackbar"),

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@ public ToastPage(ToastViewModel toastViewModel) : base(toastViewModel)
async void ShowToastButtonClicked(object? sender, EventArgs args)
{
var toast = Toast.Make("This is a default Toast.");
await toast.Show();

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await toast.Show(cts.Token);
}

async void ShowCustomToastButtonClicked(object? sender, EventArgs args)
{
var toast = Toast.Make("This is a big Toast.", ToastDuration.Long, 30d);
await toast.Show();

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await toast.Show(cts.Token);
}

async void DisplayToastInModalButtonClicked(object? sender, EventArgs e)
Expand All @@ -37,7 +41,7 @@ await Application.Current.MainPage.Navigation.PushModalAsync(new ContentPage

Children =
{
new Button { Command = new AsyncRelayCommand(() => Toast.Make("Toast in a Modal Page").Show()) }
new Button { Command = new AsyncRelayCommand(token => Toast.Make("Toast in a Modal Page").Show(token)) }
.Top().CenterHorizontal()
.Text("Display Toast"),

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="AnimationBehavor is a Behavior that can be attached to any VisualElement, allowing developers to: trigger animations via: ICommand AnimateCommand." />
<Span Text="AnimationBehavior is a Behavior that can be attached to any VisualElement, allowing developers to: trigger animations via: ICommand AnimateCommand." />
<Span Text="{x:Static system:Environment.NewLine}" />
<Span Text="* use the default of a TapGestureRecognizer being added to the attached VisualElement" />
<Span Text="{x:Static system:Environment.NewLine}" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,17 @@ public AnimationBehaviorPage(AnimationBehaviorViewModel animationBehaviorViewMod

class SampleScaleAnimation : BaseAnimation
{
public override async Task Animate(VisualElement view)
public override async Task Animate(VisualElement view, CancellationToken token)
{
await view.ScaleTo(1.2, Length, Easing);
await view.ScaleTo(1, Length, Easing);
await view.ScaleTo(1.2, Length, Easing).WaitAsync(token);
await view.ScaleTo(1, Length, Easing).WaitAsync(token);
}
}

class SampleScaleToAnimation : BaseAnimation
{
public double Scale { get; set; }

public override Task Animate(VisualElement view) => view.ScaleTo(Scale, Length, Easing);
public override Task Animate(VisualElement view, CancellationToken token)
=> view.ScaleTo(Scale, Length, Easing).WaitAsync(token);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ async void SetEntryValue(object? sender, EventArgs e)
{
var toastVisibilityTimeSpan = TimeSpan.FromSeconds(5);
var cts = new CancellationTokenSource(toastVisibilityTimeSpan);

await Toast.Make($"The app will crash because `null` is an invalid value for {nameof(NumericValidationBehavior)}.\nOptionally, {nameof(Options)}.{nameof(Options.SetShouldSuppressExceptionsInBehaviors)} can be set to true", Core.ToastDuration.Long).Show(cts.Token);

await Task.Delay(toastVisibilityTimeSpan, cts.Token);

SafeEntry.Text = null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,39 @@ public partial class AvatarViewGesturesPage : BasePage<AvatarViewGesturesViewMod
{
public AvatarViewGesturesPage(AvatarViewGesturesViewModel avatarViewGesturesViewModel) : base(avatarViewGesturesViewModel) => InitializeComponent();

async void DragGestureRecognizer_DragStarting(object sender, DragStartingEventArgs e) => await ShowToastGestureMessage("AvatarView drag gesture recognizer, drag starting.");
async void DragGestureRecognizer_DragStarting(object sender, DragStartingEventArgs e)
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await ShowToastGestureMessage("AvatarView drag gesture recognizer, drag starting.", cts.Token);
}

async void PanGestureRecognizer_PanUpdated(object sender, PanUpdatedEventArgs e) => await ShowToastGestureMessage("AvatarView pan gesture recognizer, pan updated.");
async void PanGestureRecognizer_PanUpdated(object sender, PanUpdatedEventArgs e)
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await ShowToastGestureMessage("AvatarView pan gesture recognizer, pan updated.", cts.Token);
}

async void PinchGestureRecognizer_PinchUpdated(object sender, PinchGestureUpdatedEventArgs e) => await ShowToastGestureMessage("AvatarView pinch gesture recognizer, pinch updated.");
async void PinchGestureRecognizer_PinchUpdated(object sender, PinchGestureUpdatedEventArgs e)
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await ShowToastGestureMessage("AvatarView pinch gesture recognizer, pinch updated.", cts.Token);
}

async void SwipeGestureRecognizer_Swiped(object sender, SwipedEventArgs e) => await ShowToastGestureMessage("AvatarView swipe gesture recognizer, swiped.");
async void SwipeGestureRecognizer_Swiped(object sender, SwipedEventArgs e)
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await ShowToastGestureMessage("AvatarView swipe gesture recognizer, swiped.", cts.Token);
}

async void TapGestureRecognizer_Tapped(object sender, EventArgs e) => await ShowToastGestureMessage("AvatarView Tap Gesture Recognizer, tapped.");
async void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await ShowToastGestureMessage("AvatarView Tap Gesture Recognizer, tapped.", cts.Token);
}

static async Task ShowToastGestureMessage(string message)
static Task ShowToastGestureMessage(string message, CancellationToken token)
{
Core.IToast toast = Toast.Make(message, Core.ToastDuration.Short);
await toast.Show();
return toast.Show(token);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,29 @@ void LoadPointsButtonClicked(object sender, EventArgs e)

async void GetCurrentDrawingViewImageClicked(object sender, EventArgs e)
{
var stream = await DrawingViewControl.GetImageStream(GestureImage.Width, GestureImage.Height);
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var stream = await DrawingViewControl.GetImageStream(GestureImage.Width, GestureImage.Height, cts.Token);

GestureImage.Source = ImageSource.FromStream(() => stream);
}

async void GenerateImageButtonClicked(object sender, EventArgs e)
{
var lines = GenerateLines(2);
await DrawImage(lines);

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await DrawImage(lines, cts.Token);
}

async Task DrawImage(IEnumerable<DrawingLine> lines)
async Task DrawImage(IEnumerable<DrawingLine> lines, CancellationToken token)
{
var drawingLines = lines.ToList();
var points = drawingLines.SelectMany(x => x.Points).ToList();
var stream = await DrawingView.GetImageStream(drawingLines,
new Size(points.Max(x => x.X) - points.Min(x => x.X), points.Max(x => x.Y) - points.Min(x => x.Y)),
Colors.Gray);
Colors.Gray,
token);

GestureImage.Source = ImageSource.FromStream(() => stream);
}

Expand All @@ -71,7 +77,10 @@ async void OnDrawingLineCompleted(object sender, DrawingLineCompletedEventArgs e
{
var width = GetSide(GestureImage.Width);
var height = GetSide(GestureImage.Height);
var stream = await e.LastDrawingLine.GetImageStream(width, height, Colors.Gray.AsPaint());

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var stream = await e.LastDrawingLine.GetImageStream(width, height, Colors.Gray.AsPaint(), cts.Token);

GestureImage.Source = ImageSource.FromStream(() => stream);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ namespace CommunityToolkit.Maui.Sample.Pages.Views.LazyView;

public class CustomLazyView<TView> : Maui.Views.LazyView where TView : View, new()
{
public override async ValueTask LoadViewAsync()
public override async ValueTask LoadViewAsync(CancellationToken token)
{
// display a loading indicator
Content = new ActivityIndicator { IsRunning = true }.Center();

// simulate a long running task
await Task.Delay(3000);
await Task.Delay(3000, token);

// load the view
Content = new TView { BindingContext = BindingContext };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
<Label Text="Lazy Loading Based On User Action" Style="{StaticResource Heading}"/>
<Label Text="{Binding Source={x:Reference LazyUserAction}, Path=HasLazyViewLoaded, StringFormat='HasLazyViewLoaded = {0}'}" Style="{StaticResource Heading}"/>
<Button Text="Load View Now" Clicked="LoadLazyView_Clicked" WidthRequest="200" IsVisible="{Binding Source={x:Reference LazyUserAction}, Path=HasLazyViewLoaded, Converter={mct:InvertedBoolConverter}}" />
<local:MyLazyView x:Name="LazyUserAction" Style="{StaticResource MyViewStyle}"/>
<local:MyViewLazyView x:Name="LazyUserAction" Style="{StaticResource MyViewStyle}"/>
</VerticalStackLayout>
</ScrollView>
</pages:BasePage>
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@ public LazyViewPage(LazyViewViewModel viewModel) : base(viewModel)
protected override async void OnAppearing()
{
base.OnAppearing();
await LazyActiviation.LoadViewAsync();

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await LazyActiviation.LoadViewAsync(cts.Token);
}

async void LoadLazyView_Clicked(object sender, EventArgs e)
{
await LazyUserAction.LoadViewAsync();
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await LazyUserAction.LoadViewAsync(cts.Token);
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using CommunityToolkit.Maui.Views;

namespace CommunityToolkit.Maui.Sample.Pages.Views.LazyView;

class MyViewLazyView : LazyView<MyView>
{
public override async ValueTask LoadViewAsync(CancellationToken token)
{
await base.LoadViewAsync(token);
}
}
Loading