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

299 views Asked by At

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...

1

There are 1 answers

1
David Heffernan On BEST ANSWER

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