Does this Resharper solution mean a closed close problem?

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 ?

+6
source share
3 answers

You mix ReSharper quick fix and contextual action. When ReSharper offers to fix something, most likely you will see a lamp there. You do not see the lamp here, because a quick warning about this warning does not exist.

But in addition to quick fixes, ReSharper also has “contextual actions” where it can perform some routine tasks for you (think of them as small refactoring). When ReSharper has a context action for the code under the cursor, it will show you the choice. Here you see a context action called "Check, something is not empty." It has nothing to do with the warning, and there is no agreement that after deleting the variable it will be set to null.

In addition, when you press Alt-Enter, you will see a lighted bulb to give the impression that ReSharper does not offer quick fixes for this warning, but can disable it with comments. In fact, the only way to make this warning is to disappear easily. But instead, I would rewrite this piece of code.

+6
source

I came across exactly this just a few hours ago.

This is a false alarm. R # does not understand that execution will be blocked until an event is set, even if it cancels the deletion until the right moment.

IMO is a good solution. Just ignore R #.

Suggest to catch ObjectDisposedException when you call completedEvent.Set() , in case of timeout and event expiration. I don't think this will prevent the R # warning, but it is safe.

+2
source

I think you should check for null, moreover you should catch this exception. Imagine what happens if someFunc works more than timeoutMilliseconds .

+1
source

All Articles