C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# RegNotifyChangeKeyValue监听注册表

C#使用RegNotifyChangeKeyValue监听注册表更改的方法小结

作者:HRESULT

RegNotifyChangeKeyValue的最后一个参数传递false,表示以同步的方式监听,这篇文章主要介绍了C#使用RegNotifyChangeKeyValue监听注册表更改的方法小结,需要的朋友可以参考下

养成一个好习惯,调用 Windows API 之前一定要先看文档

RegNotifyChangeKeyValue 函数 (winreg.h) - Win32 apps | Microsoft Learn

同步阻塞模式

RegNotifyChangeKeyValue的最后一个参数传递false,表示以同步的方式监听。
同步模式会阻塞调用线程,直到监听的目标发生更改才会返回,如果在UI线程上调用,则会导致界面卡死,因此我们一般不会直接在主线程上同步监听,往往是创建一个新的线程来监听。

示例代码因为是控制台程序,因此没有创建新的线程。

RegistryKey hKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\1-RegMonitor");
string changeBefore = hKey.GetValue("TestValue").ToString();
Console.WriteLine($"TestValue的当前值是:{changeBefore}, 时间:{DateTime.Now:HH:mm:ss}");
//此处创建一个任务,5s之后修改TestValue的值为一个新的guid
Task.Delay(5000).ContinueWith(t =>
{
    string newValue = Guid.NewGuid().ToString();
    Console.WriteLine($"TestValue的值即将被改为:{newValue}, 时间:{DateTime.Now:HH:mm:ss}");
    hKey.SetValue("TestValue", newValue);
});
int ret = RegNotifyChangeKeyValue(hKey.Handle, false, RegNotifyFilter.ChangeLastSet, new SafeWaitHandle(IntPtr.Zero, true), false);
if(ret != 0)
{
    Console.WriteLine($"出错了:{ret}");
    return;
}
string currentValue = hKey.GetValue("TestValue").ToString();
Console.WriteLine($"TestValue的最新值是:{currentValue}, 时间:{DateTime.Now:HH:mm:ss}");
hKey.Close();
Console.ReadLine();

运行结果:

异步模式

RegNotifyChangeKeyValue的最后一个参数传递true,表示以异步的方式监听。
异步模式的关键点是需要创建一个事件,然后RegNotifyChangeKeyValue会立即返回,不会阻塞调用线程,然后需要在其他的线程中等待事件的触发。
当然也可以在RegNotifyChangeKeyValue返回之后立即等待事件,这样跟同步阻塞没有什么区别,如果不是出于演示目的,则没什么意义。

出于演示目的毫无意义的异步模式示例:

RegistryKey hKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\1-RegMonitor");
string changeBefore = hKey.GetValue("TestValue").ToString();
Console.WriteLine($"TestValue的当前值是:{changeBefore}, 时间:{DateTime.Now:HH:mm:ss}");
//此处创建一个任务,5s之后修改TestValue的值为一个新的guid
Task.Delay(5000).ContinueWith(t =>
{
    string newValue = Guid.NewGuid().ToString();
    Console.WriteLine($"TestValue的值即将被改为:{newValue}, 时间:{DateTime.Now:HH:mm:ss}");
    hKey.SetValue("TestValue", newValue);
});
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
int ret = RegNotifyChangeKeyValue(hKey.Handle, false, RegNotifyFilter.ChangeLastSet, manualResetEvent.SafeWaitHandle, true);
if(ret != 0)
{
    Console.WriteLine($"出错了:{ret}");
    return;
}
Console.WriteLine($"RegNotifyChangeKeyValue立即返回,时间:{DateTime.Now:HH:mm:ss}");
manualResetEvent.WaitOne();
string currentValue = hKey.GetValue("TestValue").ToString();
Console.WriteLine($"TestValue的最新值是:{currentValue}, 时间:{DateTime.Now:HH:mm:ss}");
hKey.Close();
manualResetEvent.Close();
Console.WriteLine("收工");
Console.ReadLine();

运行结果:

正经的代码大概应该这么写:

演示代码请忽略参数未判空,异常未处理等场景

class RegistryMonitor
{
    private Thread m_thread = null;
    private string m_keyName;
    private RegNotifyFilter m_notifyFilter = RegNotifyFilter.ChangeLastSet;
    public event EventHandler RegistryChanged;
    public RegistryMonitor(string keyName, RegNotifyFilter notifyFilter)
    {
        this.m_keyName = keyName;
        this.m_notifyFilter = notifyFilter;
        this.m_thread = new Thread(ThreadAction);
        this.m_thread.IsBackground = true;
    }
    public void Start()
    {
        this.m_thread.Start();
    }
    private void ThreadAction()
    {
        using(RegistryKey hKey = Registry.CurrentUser.CreateSubKey(this.m_keyName))
        {
            using(ManualResetEvent waitHandle = new ManualResetEvent(false))
            {
                int ret = RegNotifyChangeKeyValue(hKey.Handle, false, this.m_notifyFilter, waitHandle.SafeWaitHandle, true);
                waitHandle.WaitOne();
                this.RegistryChanged?.Invoke(this, EventArgs.Empty);
            }
        }
    }
}
static void Main(string[] args)
{
    string keyName = "SOFTWARE\\1-RegMonitor";
    RegistryKey hKey = Registry.CurrentUser.CreateSubKey(keyName);
    string changeBefore = hKey.GetValue("TestValue").ToString();
    Console.WriteLine($"TestValue的当前值是:{changeBefore}, 时间:{DateTime.Now:HH:mm:ss}");
    //此处创建一个任务,5s之后修改TestValue的值为一个新的guid
    Task.Delay(5000).ContinueWith(t =>
    {
        string newValue = Guid.NewGuid().ToString();
        Console.WriteLine($"TestValue的值即将被改为:{newValue}, 时间:{DateTime.Now:HH:mm:ss}");
        hKey.SetValue("TestValue", newValue);
    });
    RegistryMonitor monitor = new RegistryMonitor(keyName, RegNotifyFilter.ChangeLastSet);
    monitor.RegistryChanged += (sender, e) =>
    {
        Console.WriteLine($"{keyName}的值发生了改变");
        string currentValue = hKey.GetValue("TestValue").ToString();
        Console.WriteLine($"TestValue的最新值是:{currentValue}, 时间:{DateTime.Now:HH:mm:ss}");
        hKey.Close();
    };
    monitor.Start();
    Console.WriteLine("收工");
    Console.ReadLine();
}

运行结果:

那么问题来了:

接下来 ,我们尝试改造一下

基于线程池的异步模式

调用线程池的RegisterWaitForSingleObject,给一个事件注册一个回调,当事件触发时,则执行指定的回调函数,参考ThreadPool.RegisterWaitForSingleObject 方法 (System.Threading) | Microsoft Learn

代码实例如下:

class RegistryMonitor
{
    private string m_keyName;
    private RegNotifyFilter m_notifyFilter = RegNotifyFilter.ChangeLastSet;
    private RegisteredWaitHandle m_registered = null;
    private RegistryKey m_key = null;
    private ManualResetEvent m_waitHandle = null;
    public event EventHandler RegistryChanged;
    public RegistryMonitor(string keyName, RegNotifyFilter notifyFilter)
    {
        this.m_keyName = keyName;
        this.m_notifyFilter = notifyFilter;
    }
    public void Start()
    {
        this.m_key = Registry.CurrentUser.CreateSubKey(this.m_keyName);
        this.m_waitHandle = new ManualResetEvent(false);
        int ret = RegNotifyChangeKeyValue(this.m_key.Handle, false, this.m_notifyFilter | RegNotifyFilter.ThreadAgnostic, this.m_waitHandle.SafeWaitHandle, true);
        this.m_registered = ThreadPool.RegisterWaitForSingleObject(this.m_waitHandle, Callback, null, Timeout.Infinite, true);
    }
    private void Callback(object state, bool timedOut)
    {
        this.m_registered.Unregister(this.m_waitHandle);
        this.m_waitHandle.Close();
        this.m_key.Close();
        this.RegistryChanged?.Invoke(this, EventArgs.Empty);
    }
}
static void Main(string[] args)
{
    for(int i = 1; i <= 50; i++)
    {
        string keyName = $"SOFTWARE\\1-RegMonitor\\{i}";
        RegistryKey hKey = Registry.CurrentUser.CreateSubKey(keyName);
        hKey.SetValue("TestValue", Guid.NewGuid().ToString());
        string changeBefore = hKey.GetValue("TestValue").ToString();
        Console.WriteLine($"{keyName} TestValue的当前值是:{changeBefore}, 时间:{DateTime.Now:HH:mm:ss}");
        RegistryMonitor monitor = new RegistryMonitor(keyName, RegNotifyFilter.ChangeLastSet);
        monitor.RegistryChanged += (sender, e) =>
        {
            Console.WriteLine($"{keyName}的值发生了改变");
            string currentValue = hKey.GetValue("TestValue").ToString();
            Console.WriteLine($"{keyName} TestValue的最新值是:{currentValue}, 时间:{DateTime.Now:HH:mm:ss}");
            hKey.Close();
        };
        monitor.Start();
        Console.WriteLine($"{keyName}监听中...");
    }
    Console.WriteLine("收工");
    Console.ReadLine();
}

运行结果:

可以看到,创建50个监听,而进程的总线程数只有7个。因此使用线程池是最佳方案。

注意事项

基础代码

/// <summary>
/// 指示应报告的更改
/// </summary>
[Flags]
enum RegNotifyFilter
{
    /// <summary>
    /// 通知调用方是添加还是删除了子项
    /// </summary>
    ChangeName = 0x00000001,
    /// <summary>
    /// 向调用方通知项属性(例如安全描述符信息)的更改
    /// </summary>
    ChangeAttributes = 0x00000002,
    /// <summary>
    /// 向调用方通知项值的更改。 这包括添加或删除值,或更改现有值
    /// </summary>
    ChangeLastSet = 0x00000004,
    /// <summary>
    /// 向调用方通知项的安全描述符的更改
    /// </summary>
    ChangeSecurity = 0x00000008,
    /// <summary>
    /// 指示注册的生存期不得绑定到发出 RegNotifyChangeKeyValue 调用的线程的生存期。<b>注意</b> 此标志值仅在 Windows 8 及更高版本中受支持。
    /// </summary>
    ThreadAgnostic = 0x10000000
}
/// <summary>
/// 通知调用方对指定注册表项的属性或内容的更改。
/// </summary>
/// <param name="hKey">打开的注册表项的句柄。密钥必须已使用KEY_NOTIFY访问权限打开。</param>
/// <param name="bWatchSubtree">如果此参数为 TRUE,则函数将报告指定键及其子项中的更改。 如果参数为 FALSE,则函数仅报告指定键中的更改。</param>
/// <param name="dwNotifyFilter">
/// 一个值,该值指示应报告的更改。 此参数可使用以下一个或多个值。<br/>
/// REG_NOTIFY_CHANGE_NAME 0x00000001L 通知调用方是添加还是删除了子项。<br/>
/// REG_NOTIFY_CHANGE_ATTRIBUTES 0x00000002L 向调用方通知项属性(例如安全描述符信息)的更改。<br/>
/// REG_NOTIFY_CHANGE_LAST_SET 0x00000004L 向调用方通知项值的更改。 这包括添加或删除值,或更改现有值。<br/>
/// REG_NOTIFY_CHANGE_SECURITY 0x00000008L 向调用方通知项的安全描述符的更改。<br/>
/// REG_NOTIFY_THREAD_AGNOSTIC 0x10000000L 指示注册的生存期不得绑定到发出 RegNotifyChangeKeyValue 调用的线程的生存期。<b>注意</b> 此标志值仅在 Windows 8 及更高版本中受支持。
/// </param>
/// <param name="hEvent">事件的句柄。 如果 fAsynchronous 参数为 TRUE,则函数将立即返回 ,并通过发出此事件信号来报告更改。 如果 fAsynchronous 为 FALSE,则忽略 hEvent 。</param>
/// <param name="fAsynchronous">
/// 如果此参数为 TRUE,则函数将立即返回并通过向指定事件发出信号来报告更改。 如果此参数为 FALSE,则函数在发生更改之前不会返回 。<br/>
/// 如果 hEvent 未指定有效的事件, 则 fAsynchronous 参数不能为 TRUE。
/// </param>
/// <returns></returns>
[DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int RegNotifyChangeKeyValue(SafeHandle hKey, bool bWatchSubtree, RegNotifyFilter dwNotifyFilter, SafeHandle hEvent, bool fAsynchronous);

到此这篇关于C#使用RegNotifyChangeKeyValue监听注册表更改的几种方式的文章就介绍到这了,更多相关C# RegNotifyChangeKeyValue监听注册表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文