Обработчик прерывания консольного приложения по Ctrl+C#1512
Обработчик прерывания консольного приложения по Ctrl+C#1512EvilBeaver merged 2 commits intodevelopfrom
Conversation
WalkthroughThe changes update the event processing and dependency injection model across several components. The modifications remove redundant event processor assignments and enforce lazy loading in the machine instance. Enhancements include robust handling of the Ctrl+C console event in the console context, updates to console provider construction, and improved thread safety in event handler registration. Additionally, new extension methods for engine building are added, and a service getter is exposed to enable external access to engine services. Changes
Sequence Diagram(s)sequenceDiagram
participant U as User
participant C as Console
participant CC as ConsoleContext
participant EC as ExecutionContext
participant EP as IEventProcessor
U->>C: Press Ctrl+C
C->>CC: Trigger CancelKeyPress event
CC->>EC: TryResolve(IEventProcessor)
EC-->>CC: Return EP instance (or null)
alt EP resolved
CC->>EP: HandleEvent(cancelRef)
EP-->>CC: Return cancellation decision
CC->>C: Set e.Cancel based on decision
else EP not resolved
CC->>C: Proceed with default cancellation
end
Poem
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (5)
src/ScriptEngine.HostedScript/HostedScriptEngine.cs (1)
131-132: Consider documenting the service container's intended usage.The new property exposes the engine's service container, which is a significant architectural change. While this exposure appears intentional based on the PR objectives, it would be beneficial to add XML documentation comments explaining:
- The intended usage of this property
- Any limitations or threading considerations
- Whether this is meant for internal framework use or public consumption
+ /// <summary> + /// Gets the service container associated with the scripting engine. + /// This container provides access to registered engine services and event handlers. + /// </summary> public IServiceContainer Services => _engine.Services;src/ScriptEngine.HostedScript/DefaultEventProcessor.cs (2)
61-63: Immutable dictionary reference.
Making_registeredHandlersreadonly prevents accidental reassignment. If you anticipate heavy concurrency, consider a specialized concurrent collection in the future.
75-90: Thread-safe subscription logic.
Locking_subscriptionLockensures atomic creation and retrieval of handlers. For completeness, consider null or empty checks oneventNameif external input is possible.src/OneScript.StandardLibrary/Text/ConsoleProvider.cs (1)
22-24: Constructor withExecutionContext.
Accepting anExecutionContextparameter enables context-aware initialization, reducing coupling and improving flexibility for different runtime scenarios.src/OneScript.StandardLibrary/Text/ConsoleContext.cs (1)
282-306: Robust implementation of Ctrl+C handling.The implementation:
- Properly checks for Ctrl+C specifically
- Safely resolves the event processor
- Sets up the execution context and debugger
- Handles the cancel variable correctly
- Properly propagates the cancellation decision
However, consider adding a comment explaining why we're not handling exceptions in the event handler (line 302).
- // Вызываем обработчик. Исключение в обработчике никак отдельно не обрабатываем. + // Вызываем обработчик. Исключения в обработчике не перехватываем, так как они должны + // прерывать выполнение программы, как и в случае необработанного Ctrl+C.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
src/OneScript.StandardLibrary/Tasks/BackgroundTasksManager.cs(0 hunks)src/OneScript.StandardLibrary/Text/ConsoleContext.cs(2 hunks)src/OneScript.StandardLibrary/Text/ConsoleProvider.cs(3 hunks)src/ScriptEngine.HostedScript/DefaultEventProcessor.cs(4 hunks)src/ScriptEngine.HostedScript/Extensions/EngineBuilderExtensions.cs(1 hunks)src/ScriptEngine.HostedScript/HostedScriptEngine.cs(2 hunks)src/ScriptEngine.HostedScript/Process.cs(0 hunks)src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs(1 hunks)src/ScriptEngine/Machine/MachineInstance.cs(5 hunks)src/oscript/ConsoleHostBuilder.cs(1 hunks)
💤 Files with no reviewable changes (2)
- src/OneScript.StandardLibrary/Tasks/BackgroundTasksManager.cs
- src/ScriptEngine.HostedScript/Process.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: SonarQube
🔇 Additional comments (18)
src/ScriptEngine.HostedScript/HostedScriptEngine.cs (1)
15-15: LGTM!The added using directive is required for the new
IServiceContainertype and follows proper ordering.src/ScriptEngine.HostedScript/DefaultEventProcessor.cs (6)
29-29: Use ofreadonlyis beneficial.
Marking the_handlersfield asreadonlyreinforces immutability of the reference, improving code stability.
64-64: Dedicated lock object.
Introducing_subscriptionLockis a clear concurrency approach, avoiding collisions with other locks.
102-113: Consistent removal synchronization.
Lock usage here matches the pattern inAddHandler, maintaining thread safety for unsubscriptions.
118-119: Method signature update for concurrency.
The introduction of a localHandlersListreference prepares for safe enumeration outside the lock.
120-130: Local copy creation within the lock.
Extracting the reference insideHandleEvent’s lock then iterating outside prevents mid-iteration modifications.
132-132: Safe iteration of handlers.
Looping overhandlersLocalCopyavoids concurrency pitfalls and race conditions if the handlers dictionary changes elsewhere.src/oscript/ConsoleHostBuilder.cs (1)
54-54: Enabling event handlers.
Appending.UseEventHandlers()cleanly wires up the default event processing, clarifying the engine’s event-driven capabilities.src/OneScript.StandardLibrary/Text/ConsoleProvider.cs (3)
10-11: Additional namespace imports.
The newusingdirectives ensure easy integration with dependency injection and type utilities.
20-20:readonly_consolefield.
This field’s immutability helps maintain consistent references to the console context.
51-53: Factory method modernization.
ProvidingCreateInstance(ExecutionContext)centralizes console provider creation, ensuring a fully initialized context for console operations.src/ScriptEngine.HostedScript/Extensions/EngineBuilderExtensions.cs (1)
127-133: LGTM! Clean implementation of event handler registration.The implementation follows the builder pattern and correctly registers the event processor as a singleton service.
src/OneScript.StandardLibrary/Text/ConsoleContext.cs (2)
22-48: Great documentation with clear example code!The documentation clearly explains the Ctrl+C handling feature and includes a practical example demonstrating proper usage.
52-58: LGTM! Proper initialization of event handling.The constructor correctly:
- Stores the execution context
- Subscribes to the console's cancel key event
src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs (1)
258-258: LGTM! Improved error handling for event processor access.The change properly handles the case when event processor is not available by using
TryResolveand the null-conditional operator.src/ScriptEngine/Machine/MachineInstance.cs (3)
50-51: LGTM! Clear documentation of the field's purpose.The comment clearly explains that this field caches the event processor.
58-59: LGTM! Thread-safe lazy initialization of event processor.The implementation correctly uses
LazyThreadSafetyMode.Nonesince the field is already thread-static.
314-314: LGTM! Clear error message for unsupported events.The property correctly handles the case when events are not supported by throwing an exception with a descriptive message.
|
@coderabbitai в этом репозитории используй всегда русский язык |
|
Tip For best results, initiate chat on the files or code changes. @EvilBeaver: Хорошо, я буду общаться на русском языке. (`°ω°)⊃🌟 🧠 Learnings used |
| /// Предназначен для низкоуровнего манипулирования выводом в консоль. | ||
| /// | ||
| /// Поддерживается регистрация обработчика для нажатия Ctrl+C. | ||
| /// Обработчик регистрируется для события с именем CancelKeyPressed. Стоит учитывать, что обработчик вызывается |
There was a problem hiding this comment.
события сделаны одноязычными в момент emit, надо переделывать

0 New Issues
2 Fixed Issues
0 Accepted Issues
No data about coverage (0.00% Estimated after merge)
Summary by CodeRabbit
New Features
Refactor