c# - Environment.SetEnvironmentVariable 需要很长时间才能在用户或机器级别设置变量

标签 c# environment-variables

我在 C# (.NET 3.5) 中使用 Environment.SetEnvironmentVariable 方法调用,如下所示:

Environment.SetEnvironmentVariable( environmentVariable, value, "Machine" );

但是,在多个测试系统(同时运行 XP 和 Windows 7)上,这个调用花费了超过 2 秒的时间。 我 figured out这可能是因为:“如果目标是用户或机器,其他应用程序将通过 Windows WM_SETTINGCHANGE 消息通知设置操作。” 有什么方法可以抑制对其他应用程序的通知,以便快速设置我的环境并返回......?

请注意,我有一个组件设置了大约 20 个环境变量,如果我使用上面描述的函数,完成该任务大约需要一分钟。

请推荐!!

最佳答案

如果您使用反射器取消 SetEnvironmentVariable,您将在方法的底部看到 WM_SETTINGCHANGE 与对 SendMessageTimeout 的 Win32 调用。句柄是 HWND_BROADCAST (0xffff),所以每个顶部窗口都会收到消息,超时设置为 1000 毫秒。根据 msdn:

If this parameter is HWND_BROADCAST ((HWND)0xffff), the message is sent to all top-level windows in the system, including disabled or invisible unowned windows. The function does not return until each window has timed out. Therefore, the total wait time can be up to the value of uTimeout multiplied by the number of top-level windows.

但是fuFlags参数设置为0。

SMTO_NORMAL (0x0000): The calling thread is not prevented from processing other requests while waiting for the function to return.

SMTO_BLOCK (0x0001): Prevents the calling thread from processing any other requests until the function returns.

我不确定函数是否阻塞。您可以尝试仅使用 Win32 设置变量,并在设置所有变量后才发送广播消息。或者您可以直接访问注册表。

关于c# - Environment.SetEnvironmentVariable 需要很长时间才能在用户或机器级别设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4825967/

相关文章:

c# - 获取InvalidOperationException错误堆栈跟踪只有一行

c# - 输入时移除按钮边框

c# - 为了鼠标事件,如何将 Popup 包含在它的父控件中?

javascript - 从代码隐藏中的javascript函数检索值

python - os.environ ['PATH' ] 与 echo %PATH% 不匹配

java - 公共(public)执行 : Executing a program on the system PATH?

python - Python 中有没有一种方法可以检查 os.environ 的条目是变量还是 shell 函数?

c# - 在 platform.uno 项目中引用 .netstandard2_0 项目

javascript - 如何在不重建 React 应用程序镜像的情况下更新环境变量

ruby-on-rails - 环境变量在cloud9中如何工作