AaTurpin.SleepManager 1.2.0

The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package AaTurpin.SleepManager --version 1.2.0
                    
NuGet\Install-Package AaTurpin.SleepManager -Version 1.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AaTurpin.SleepManager" Version="1.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AaTurpin.SleepManager" Version="1.2.0" />
                    
Directory.Packages.props
<PackageReference Include="AaTurpin.SleepManager" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add AaTurpin.SleepManager --version 1.2.0
                    
#r "nuget: AaTurpin.SleepManager, 1.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package AaTurpin.SleepManager@1.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=AaTurpin.SleepManager&version=1.2.0
                    
Install as a Cake Addin
#tool nuget:?package=AaTurpin.SleepManager&version=1.2.0
                    
Install as a Cake Tool

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

  1. No longer required: Call AllowSleep() when your application is done (automatic cleanup handles this in v1.2.0, but it's still good practice).
  2. For long-running applications, consider using PreventSleepTemporarilyAsync() instead of managing the state manually.
  3. Only prevent sleep when absolutely necessary to conserve energy.
  4. Remember that sleep prevention is tied to the thread that activated it. Ensure your application architecture accounts for this.
  5. 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:

  1. Added "automatic sleep restoration" to the Features section
  2. Updated Basic Usage example with a comment about exit handlers
  3. Updated Console Application example with a comment about automatic cleanup
  4. Added comprehensive "What's New in Version 1.2.0" section
  5. Added "Previous Version History" section to track v1.1.0 changes
  6. Updated "How It Works" section with information about automatic exit handlers
  7. Updated "Best Practices" section noting that manual cleanup is now optional
  8. Updated "Logging" section to include the new logging features
Product Compatible and additional computed target framework versions.
.NET Framework net472 is compatible.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETFramework 4.7.2

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