Using KeyWord + Lambda Expressions

I found some weird code in an old project that looks like this:

using (var removeGroupMembershipWorker = new BackgroundWorker())
{
    removeGroupMembershipWorker.DoWork += (senderRGMW, eRGMW) =>
    {

    };
    removeGroupMembershipWorker.RunWorkerAsync();
}

      

The code in the lambda is rejected.

For me, the keyword using

and the lambda expression don't mix together: Lambda has to use an object at the class level, otherwise the code cannot be called later.

But how does the keyword work here using

? The thread is obviously not waiting for Async to complete, but what happens when a block remains using

?

Is it using

easy to ignore in such cases?

Edith says: "Since I am missing Raghus's answer and this excellent link; I am adding it here: http://softwareblog.alcedo.com/post/2011/12/09/Using-blocks-and-asynchronous-operations.aspx
This explains problem and solution to the problem.

+3


source to share


1 answer


The block using

is syntactic sugar for the try

... construct finally

, in which the block finally

calls a method on the IDisposable.Dispose()

object. Of course, this means that the available object must implement IDisposable

, otherwise you will get a compile-time error.

Calling Dispose()

is not the same as allowing an object to go out of scope for garbage collection. In particular, if the code inside the lambda refers to a removeGroupMembershipWorker

closure path, the lambda may end up with a reference to the object that was deleted. This script may or may not throw errors, depending on what it actually does Dispose()

.



So, as you remember, a template using

might not be the best idea here. If you need to call Dispose()

- which you really need for anyone IDisposable

- you can call it directly when it's safe to do so. What "safe for this" means depends on your code, but essentially Dispose()

should be the last method called by the object (excluding any methods called internally Dispose()

, of course).

+2


source







All Articles