Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment.SetEnvironmentVariable takes a long time to set a variable at User or Machine level

I am using the Environment.SetEnvironmentVariable method call in C# (.NET 3.5) like this:

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

However this single call takes well over 2 seconds on several test systems (running both XP and Windows 7). I figured out that this might be because : "If target is User or Machine, other applications are notified of the set operation by a Windows WM_SETTINGCHANGE message." Is there any way to suppress this Notification to other applications so that my environment is set quickly and returns back..?

Note that I am having a component which sets around 20 environment variables and if I use the function as I have described above, it takes around a minute to finish that task.

Please suggest!!

like image 207
Santhosh Avatar asked Feb 02 '23 22:02

Santhosh


1 Answers

If you disasambly the SetEnvironmentVariable with reflector you will see at the bottom of the methode that the WM_SETTINGCHANGE with a Win32 call to SendMessageTimeout. The handle is HWND_BROADCAST (0xffff) so every top window gets the message and the timeout is set to 1000ms. According to 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.

But the fuFlags parameter is set to 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.

I'm not sure if the functions blocks or not. You can try to set the variable with only Win32 and only send the broadcast message after you set all variables. Or you can directly access the registry.

like image 152
MBulli Avatar answered Feb 05 '23 13:02

MBulli