Can I free memory allocated for parameters when SHChangeNotify is called with the SHCNF_FLUSHNOWAIT parameter?

StackOverflow https://stackoverflow.com/questions/8052496

  •  24-02-2021
  •  | 
  •  

Question

I have the following declaration for SHChangeNotify :

[DllImport("Shell32.dll")]
public static extern void SHChangeNotify(HChangeNotifyEventID wEventId, HChangeNotifyFlags uFlags, IntPtr dwItem1, IntPtr dwItem2);

Is the following code safe ?

IntPtr ptr = Marshal.StringToHGlobalUni(@"C:\foo\bar.txt");
Shell.SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, ptr, IntPtr.Zero);
Marshal.FreeHGlobal(ptr);

The doc on SHCNF_FLUSHNOWAIT states that "The function should begin delivering notifications to all affected components but should return as soon as the notification process has begun".

When I'm calling FreeHGlobal on ptr should I be worried of releasing memory that could still be used somewhere or does SHChangeNotify work on a copy of the string ?

My tests show that my code is working, but I don't want to deploy that and see problems arise later...

Was it helpful?

Solution

SHChangeNotify takes a copy of your string. You can safely, and indeed should, free the memory as soon as the call to SHChangeNotify returns.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top