AaTurpin.SleepManager
1.2.0
dotnet add package AaTurpin.SleepManager --version 1.2.0
NuGet\Install-Package AaTurpin.SleepManager -Version 1.2.0
<PackageReference Include="AaTurpin.SleepManager" Version="1.2.0" />
<PackageVersion Include="AaTurpin.SleepManager" Version="1.2.0" />
<PackageReference Include="AaTurpin.SleepManager" />
paket add AaTurpin.SleepManager --version 1.2.0
#r "nuget: AaTurpin.SleepManager, 1.2.0"
#:package AaTurpin.SleepManager@1.2.0
#addin nuget:?package=AaTurpin.SleepManager&version=1.2.0
#tool nuget:?package=AaTurpin.SleepManager&version=1.2.0
AaTurpin.SleepManager
A lightweight C# NuGet package for managing Windows system sleep settings.
Overview
AaTurpin.SleepManager is a .NET NuGet package that provides a simple interface to control the Windows system's sleep behavior. It allows your applications to temporarily prevent the system from entering sleep mode or turning off the display, which is particularly useful for long-running operations, presentations, or media playback scenarios.
The package includes and depends on RunLog 3.3.0 for comprehensive logging functionality.
Features
- Prevent system sleep with a single method call
- Optionally keep the display on while preventing sleep
- Temporarily prevent sleep for a specific duration
- Check the current sleep prevention status
- Automatic sleep restoration on application exit and unhandled exceptions
- Comprehensive logging integration
- Optimized, lightweight implementation
Requirements
- .NET Framework 4.7.2 or higher
- Windows operating system (uses Windows API P/Invoke calls)
Installation
Install the SleepManager NuGet package using the Package Manager Console:
Install-Package AaTurpin.SleepManager
Or using the .NET CLI:
dotnet add package AaTurpin.SleepManager
Package URL: NuGet Gallery
The package automatically includes RunLog as a dependency, so you don't need to install it separately.
Usage
Basic Usage
// Initialize logging first
var logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
Log.Logger = logger;
// Prevent the system from sleeping
// Exit handlers are automatically registered for cleanup
SleepManager.PreventSleep();
// Do work that shouldn't be interrupted by sleep...
// Allow system sleep again when done
SleepManager.AllowSleep();
In a Console Application
using AaTurpin.SleepManager;
using RunLog;
using System;
class Program
{
static void Main(string[] args)
{
// Configure logging
var logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console()
.CreateLogger();
Log.Logger = logger;
// Prevent sleep while application runs
// Automatic cleanup will restore sleep if app exits unexpectedly
SleepManager.PreventSleep();
Console.WriteLine("Sleep prevented. Press any key to exit and restore sleep settings.");
// Wait for user input
Console.ReadKey();
// Restore sleep settings
SleepManager.AllowSleep();
Console.WriteLine("Sleep settings restored.");
}
}
Keep Display On
// Prevent sleep and keep the display on
SleepManager.PreventSleep(keepDisplayOn: true);
Temporary Prevention
// Prevent sleep for 30 minutes
await SleepManager.PreventSleepTemporarilyAsync(TimeSpan.FromMinutes(30));
// Prevent sleep and keep display on for 5 minutes
await SleepManager.PreventSleepTemporarilyAsync(
TimeSpan.FromMinutes(5),
keepDisplayOn: true);
Check Current State
// Check if sleep is currently being prevented
bool isSleepPrevented = SleepManager.IsSleepCurrentlyPrevented();
// Check if display power-off is currently being prevented
bool isDisplayPrevented = SleepManager.IsDisplayCurrentlyPrevented();
Custom Logger
// Set a custom logger instance for the SleepManager
var customLogger = new LoggerConfiguration()
.WriteTo.File("sleep-manager-logs.txt")
.CreateLogger();
SleepManager.SetLogger(customLogger);
What's New in Version 1.2.0
- Added automatic sleep restoration on application exit - Sleep settings are now automatically restored when your application terminates normally or abnormally
- Added automatic sleep restoration on unhandled exceptions - Prevents system from remaining in prevented state during crashes
- Implemented exit handler registration with duplicate prevention - Ensures proper cleanup without performance overhead
- Enhanced PreventSleep() method - Now automatically registers cleanup handlers when sleep is prevented
- Added debug logging for exit handler registration - Improves troubleshooting and monitoring
- Improved resource management - Better handling of abnormal application termination scenarios
- Maintained backward compatibility - All existing public APIs remain unchanged
Previous Version History
Version 1.1.0
- Updated RunLog to version 3.3.0 for improved logging capabilities
- Optimized implementation with improved performance
- Simplified error handling and logging patterns
- Enhanced code readability with more consistent formatting
How It Works
SleepManager uses the Windows API function SetThreadExecutionState
to control the system's sleep behavior. This is a thread-specific setting, so the prevention only remains active as long as the thread that called the function is running.
When sleep prevention is activated, the system will not automatically enter sleep mode due to user inactivity. However, the user can still manually put the system to sleep.
New in v1.2.0: The library now automatically registers exit handlers when PreventSleep()
is called, ensuring that sleep settings are restored even if your application terminates unexpectedly.
Best Practices
- No longer required: Call
AllowSleep()
when your application is done (automatic cleanup handles this in v1.2.0, but it's still good practice). - For long-running applications, consider using
PreventSleepTemporarilyAsync()
instead of managing the state manually. - Only prevent sleep when absolutely necessary to conserve energy.
- Remember that sleep prevention is tied to the thread that activated it. Ensure your application architecture accounts for this.
- New: Take advantage of the automatic cleanup - your application will restore sleep settings even if it crashes or exits unexpectedly.
Logging
SleepManager integrates with the RunLog logging library and logs the following events:
- When sleep prevention is activated or deactivated
- When temporary sleep prevention begins and ends
- When sleep prevention state is checked
- When exit handlers are registered (debug level)
- When automatic sleep restoration occurs during exit
- Errors that occur during operation
License
MIT
Key changes made to the README for v1.2.0:
- Added "automatic sleep restoration" to the Features section
- Updated Basic Usage example with a comment about exit handlers
- Updated Console Application example with a comment about automatic cleanup
- Added comprehensive "What's New in Version 1.2.0" section
- Added "Previous Version History" section to track v1.1.0 changes
- Updated "How It Works" section with information about automatic exit handlers
- Updated "Best Practices" section noting that manual cleanup is now optional
- Updated "Logging" section to include the new logging features
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET Framework | net472 is compatible. net48 was computed. net481 was computed. |
-
.NETFramework 4.7.2
- RunLog (>= 3.3.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last Updated |
---|
Version 1.2.0 - Changes:
- Added automatic sleep restoration on application exit to prevent system from remaining in prevented state
- Added automatic sleep restoration on unhandled exceptions for improved reliability
- Implemented exit handler registration with duplicate prevention to avoid multiple handlers
- Enhanced PreventSleep() method to automatically register cleanup handlers when sleep is prevented
- Added debug logging for exit handler registration to improve troubleshooting
- Improved resource management with automatic cleanup during abnormal application termination
- Maintained backward compatibility with all existing public APIs
- Enhanced robustness of sleep state management throughout application lifecycle