Fix connect camera cancellation#3172
Conversation
There was a problem hiding this comment.
Pull request overview
This PR aims to prevent Windows crashes when navigating away from CameraView while the camera connection is still in progress, by making ConnectCamera() cancellable and guarding against double-dispose.
Changes:
- Added a handler-level
CancellationTokenSourceto cancel in-flight camera connection work. - Added an
isDisposedguard to prevent repeated disposal. - Updated
ConnectHandler()to cancel any prior connection attempt and ignore self-triggered cancellation.
src/CommunityToolkit.Maui.Camera/Handlers/CameraViewHandler.shared.cs
Outdated
Show resolved
Hide resolved
src/CommunityToolkit.Maui.Camera/Handlers/CameraViewHandler.shared.cs
Outdated
Show resolved
Hide resolved
| catch (Exception) | ||
| { | ||
| DisconnectHandler(platformView); | ||
| throw; |
There was a problem hiding this comment.
Removed the throw statement
| catch (Exception) | ||
| { | ||
| DisconnectHandler(platformView); | ||
| } |
There was a problem hiding this comment.
ConnectHandler catches all exceptions and unconditionally calls DisconnectHandler(platformView). If the handler is already disconnecting/disposing, DisconnectHandler can throw (e.g., CameraManager field already set to null and the property throws), which defeats the goal of preventing crashes. Consider guarding this path (e.g., if cancellation was requested / handler is disposed / cameraManager is null, just return), and log the exception (Trace) for non-cancellation failures before disconnecting.
Description of Change
This PR improves CameraViewHandler lifecycle by making camera connection cancellable, preventing failures when the handler is disconnected or disposed while
ConnectCamera()is still running.Changes:
cancellationTokenSourceto track and cancel camera connection.ConnectHandler()to:OperationCanceledExceptionwhen cancellation was triggered by the handler itselfDisconnectHandler()if camera connection fails for any other reasonDispose()to cancel the active token source. This ensures ongoing camera connection is cancelled if handler is disconnectedLinked Issues
PR Checklist
approved(bug) orChampioned(feature/proposal)mainat time of PRAdditional information