I am working to get rid of some warnings from static code analysis. In one specific case, deletion on ManualResetEvent not performed.
This code executes Func in the main thread and blocks the calling thread for a certain number of milliseconds. I understand that this sounds strange, but it is beyond the scope of this question, so bear with me.
Suppose I add a using statement as follows:
object result = null; using (var completedEvent = new ManualResetEvent(false)) { _dispatcher.BeginInvoke((Action)(() => { result = someFunc; completedEvent.Set(); // Here be dragons! })); completedEvent.WaitOne(timeoutMilliseconds); return result; }
Now I understand that this can cause problems. I also use Resharper and it warns me with the message "Access to remote closure".
Resharper suggests fixing this by changing the violation string to:
if (completedEvent != null) { completedEvent.Set(); }
Now the proposed solution puzzles me. Under normal circumstances, there would be no reason why a variable would be set to null by using . Is there any implementation detail for closure in .NET that guarantees that the variable will be null after the variable that has been closed is selected?
As a bonus question, would it be a good solution to the disposal problem of ManualResetEvent ?
source share