Doubt with delegates C #

5

Very good, I'm trying to understand the next part of this code ...

    public void actualizarUI(string s)
            {
                Func<int> del = delegate ()
                {
                    txttcpResultados.AppendText(s + Environment.NewLine);
                    return 0;
                };
                Invoke(del);
            }

The line of the Func<int> del = delegate () and the Invoke(del); that it does exactly? If a function is generated with a string type input parameter and none of that is set, the function would work equally ...

What benefits does it bring?

Thank you very much

    
asked by Edulon 19.06.2017 в 08:05
source

1 answer

8

The instruction

Func<int> del = delegate ()
{
   txttcpResultados.AppendText(s + Environment.NewLine);
   return 0;
};

What it does is declare a variable del whose value is a function that does not receive any parameter and returns an integer value.

This can be useful in many cases, mainly when you want to pass a method or function as an argument to another method. Typical cases of using delegates can be controllers of control events in Windows Forms or a sort function that is passed to a method in a list.

In the list handling methods you can find many examples ( Enumerable. OrderBy )

The instruction

Invoke(del);

What you are doing is calling the method Invoke of the object on which the method is executed, for the code I guess it will be a Form of Windows Forms.

What the Invoke method does is to execute the del delegate in the same thread in which the window in which the control is contained is running. This can be very practical in multi-threaded scenarios, in which the code may be running on a different thread but the interface update instructions must be executed on the same thread as the window.

Regarding the last question. If the delegate had an argument of type string you should pass it to the method Invoke . Otherwise, you will receive an exception of System.Reflection.TargetParameterCountException .

The call should be:

 Invoke(del, micadena);
    
answered by 19.06.2017 в 08:33