How to release anonymous delegates / closures in C # correctly?

I am working on a graphical application that relies heavily on delegates Action<>to customize the behavior of our user interface tools. I am wondering the way we do this is to have any potential problems, for example. Does the implementation implement references to captured variables, class instances, declaring delegates, etc.?

So, let's say we have this class MapControlthat wraps a stateful GUI control. The map has various types of tools (Drawing, Selection, etc.) represented by the interface ITool. You can install the tool with StartTool(), but you can only use one tool at a time, so when another tool is installed, the previous one stops with StopTool(). When the tool is stopped, a delegated call is made to the caller.

public class MapControl
{
    ITool _currentTool;
    Action<IResult> _onComplete;

    public void StartTool(ToolEnum tool, Action<IResult> onComplete) {

        //If tool is active, stop it first
        if (_currentTool != null) StopTool();

        _onComplete = onComplete;

        //Creates a tool class, etc.
        _currentTool = CreateTool(tool) as ITool;
    }

    public void StopTool() {

        //Execute callback delegate
        IResult result = _currentTool.GetResult();
        if (_onComplete != null)
            _onComplete(result);

        //Nix the references to callback and tool
        _onComplete = null;
        _currentTool = null;
    }
}

In the ViewModelapplication class , we install the following tool:

class ViewModel
{
    private MapControl _mapControl = new MapControl();
    public void SetSomeTool() 
    {
        //These variables will be captured in the closure
        var someClassResource = this.SomeClassResource;
        var someLocalResource = new object();

        //Start tool, specify callback delegate as lambda
        _mapControl.StartTool(ToolEnum.SelectTool, (IResult result) => {

            //Do something with result and the captured variables
            someClassResource.DoSomething(result, someLocalResource);
        });
    }
}

ViewModel WPF, ViewModel. -, , , , ?

: callback? - , , ?

, ?

+3
4

, , , . StopTool .

+2

.


, :

: callback?

( , ), .

+2

I think it would be more correct to:

_onComplete = (Action<IResult>)Delegate.Remove(null, _onComplete);
0
source

If you want you to properly manage all unused objects, I would suggest using tools like the CLR Profiler so that you can have a complete picture of how your application allocates / frees memory.

0
source

Source: https://habr.com/ru/post/1794388/


All Articles